LeetCode/solutions/226. Invert Binary Tree.md
2020-02-05 11:30:20 +08:00

54 lines
1.5 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [226. Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree/description/)
# 思路
翻转二叉树。
## 思路一
递归算法的话很简单:
* 若为空树则返回空即可。
* 令左子树指向翻转后的右子树,将右子树指向翻转后的左子树。
## 思路二
非递归算法的话类似层序遍历因为我们要交换所有节点的左右孩子所以我们用一个队列存放左右孩子还未交换的节点初始为root。然后开始循环直到队列为空出队首节点然后交换其左右孩子然后再将其左右孩子入队如果不为空的话
两个思路都相当于遍历二叉树所以时间复杂度均为O(n)空间复杂度也均为O(n)。
# C++
## 思路一
``` C++
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root == NULL) return NULL;
TreeNode *tmp = root -> left;
root -> left = invertTree(root -> right);
root -> right = invertTree(tmp);
return root;
}
};
```
## 思路二
``` C++
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root == NULL) return NULL;
queue<TreeNode *>q;
q.push(root);
TreeNode *p = NULL, *tmp = NULL;
while(!q.empty()){
p = q.front(); q.pop();
tmp = p -> left;
p -> left = p -> right;
p -> right = tmp;
if(p -> left) q.push(p -> left);
if(p -> right) q.push(p -> right);
}
return root;
}
};
```