给定一棵二叉树的根节点 root
,请左右翻转这棵二叉树,并返回其根节点。
示例 1:
输入:root = [5,7,9,8,3,2,4] 输出:[5,9,7,4,2,3,8]
提示:
- 树中节点数目范围在
[0, 100]
内 -100 <= Node.val <= 100
简单递归:
终止条件为root==null时
简单递归每日此交换root的左右子树即可
代码如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode mirrorTree(TreeNode root) {
if(root==null){
return root;
}
TreeNode t;
t=root.left;
root.left=root.right;
root.right=t;
mirrorTree(root.left);
mirrorTree(root.right);
return root;
}
}
时间复杂度O(n)
空间复杂度O(1)