226.Invert Binary Tree
给定一个二叉树,将其左右翻转。
Input:
4
/ \
2 7
/ \ / \
1 3 6 9
Output:
4
/ \
7 2
/ \ / \
9 6 3 1
思路:
递归调用,写好出口就行了。如果是叶子节点,则直接将其返回,空节点也直接返回;对于非叶子节点的,将其 root->left = invertTree(root->right),而现在的左子树就被覆盖了,如果再用 root->right = inbertTree(root->left) 就失效了,所以,需要先将左子树的节点保存下来,tmp= root->left.
TreeNode* invertTree(TreeNode* root) { if (!root) return root; if (root->left == nullptr && root->right == nullptr) return root; TreeNode* tmp = root->left; root->left = invertTree(root->right); root->right = invertTree(tmp); return root; }
Java版:
class Solution { public TreeNode invertTree(TreeNode root) { if(root == null || root.left == null && root.right == null) return root; TreeNode tmp = invertTree(root.left); root.left = invertTree(root.right); root.right = tmp; return root; } }