🍕🎉🥓🎊🚗🐷😱❤😀❣🥙🎇🕵️♀️😎🎑🎁🎉😚🎇
题目:
- 给你一棵二叉树的根节点
root
,翻转这棵二叉树,并返回其根节点。
示例:
- 输入: r o o t = [ 4 , 2 , 7 , 1 , 3 , 6 , 9 ] root = [4,2,7,1,3,6,9] root=[4,2,7,1,3,6,9]
- 输出: [ 4 , 7 , 2 , 9 , 6 , 3 , 1 ] [4,7,2,9,6,3,1] [4,7,2,9,6,3,1]
解题思路:
- 确定递归函数的参数和返回值:
void reverseTree(TreeNode* cur)
- 确定终止条件:
if(!cur) return;
- 确定单层递归逻辑: 先序遍历顺序为: 左 − > 右 − > 中 左->右->中 左−>右−>中
if(cur->left) reverseTree(cur->left);
if(cur->right) reverseTree(cur->right);
TreeNode* temp = cur->left;
cur->left = cur->right;
cur->right = temp;
C++
class Solution {
public:
void reverseTree(TreeNode* cur){
if(!cur) return;
if(cur->left) reverseTree(cur->left);
if(cur->right) reverseTree(cur->right);
TreeNode* temp = cur->left;
cur->left = cur->right;
cur->right = temp;
}
TreeNode* invertTree(TreeNode* root) {
reverseTree(root);
return root;
}
};
Java版本
class Solution {
public TreeNode reverseTree(TreeNode cur){
if(cur == null) return null;
if(cur.left != null) reverseTree(cur.left);
if(cur.right != null) reverseTree(cur.right);
TreeNode temp = cur.left;
cur.left = cur.right;
cur.right = temp;
return cur;
}
public TreeNode invertTree(TreeNode root) {
root = reverseTree(root);
return root;
}
}