LeetCode/solutions/226. Invert Binary Tree.md

22 lines
676 B
Markdown
Raw Normal View History

2018-11-03 06:36:34 +00:00
# [226. Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree/description/)
# 思路
翻转二叉树。
递归算法的话很简单:
* 若为空树则返回空即可。
* 令左子树指向翻转后的右子树,将右子树指向翻转后的左子树。
非递归算法的话用先方向层序遍历(从右到左从上到下),然后再正常层序重新赋值即可。
# 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;
}
};
```