226. Invert Binary Tree
給一棵二元樹,
要把樹上的每個節點的左右子節點都交換。
Example 1:
Input: root = [4, 2, 7, 1, 3, 6, 9]
Output: [4, 7, 2, 9, 6, 3, 1]
Explanation:
https://assets.leetcode.com/uploads/2021/03/14/invert1-tree.jpg
Example 2:
Input: root = [2, 1, 3]
Output: [2, 3, 1]
Explanation:
https://assets.leetcode.com/uploads/2021/03/14/invert2-tree.jpg
Example 3:
Input: root = []
Output: []
Explanation:
樹上沒有任何節點,直接返回空的樹
解題思路:
遞迴處理左右子節點,
然後把當前節點的左右子節點交換。
C++ code:
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(!root) return NULL;
TreeNode *temp = root->right;
root->right = invertTree(root->left);
root->left = invertTree(temp);
return root;
}
};