- Invert Binary Tree
Description
Invert a binary tree.Left and right subtrees exchange.
Example
Example 1:
Input: {1,3,#}
Output: {1,#,3}
Explanation:
1 1
/ => \
3 3
Example 2:
Input: {1,2,3,#,#,4}
Output: {1,3,2,#,4}
Explanation:
1 1
/ \ / \
2 3 => 3 2
/ \
4 4
Challenge
Do it in recursion is acceptable, can you do it without recursion?
解法1:递归。注意跟 LintCode 1360 Symmetric Tree 这题区分。这个是DFS的方法。
这个总结得很好。
https://labuladong.gitee.io/algo/di-yi-zhan-da78c/shou-ba-sh-66994/dong-ge-da-cbce8/
代码如下。
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: a TreeNode, the root of the binary tree
* @return: nothing
*/
void invertBinaryTree(TreeNode * root) {
if (!root) return;
helper(root);
return;
}
private:
TreeNode * helper(TreeNode * root) {
if (!root) return NULL;
TreeNode * origRight = root->right;
root->right = helper(root->left);
root->left = helper(origRight);
return root;
}
};
也可以
TreeNode* invertTree(TreeNode* root) {
if (!root) return NULL;
TreeNode * rootLeft = root->left; //change this line
root->left = invertTree(root->right);
root->right = invertTree(rootLeft);
return root;
}
下面的做法更简单:这个是遍历的方法。注意swap的位置可以是preorder或postorder,但不能是inorder。
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (!root) return NULL;
swap(root->left, root->right);
invertTree(root->left);
invertTree(root->right);
return root;
}
};
解法2:非递归版本。
TBD