Leetcod刷题(13)——226. 翻转二叉树

2022-06-22 14:17:32 浏览数 (1)

代码语言:javascript复制
翻转一棵二叉树。

示例:

输入:

     4
   /   
  2     7
 /    / 
1   3 6   9
输出:

     4
   /   
  7     2
 /    / 
9   6 3   1

我刚开始的想法,直接递归进行值的替换,结果竟然显示不对,一直没想明白为啥不对

代码语言:javascript复制
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode invertTree(TreeNode root) {
        if(root !=null){
            changeNode(root.left,root.right);
        }
        return root;
    }
    public void changeNode(TreeNode left,TreeNode right){
        if(left==null){
           left =right;
        }else if(right ==null){
            right=left;
        }else{
        int temp = right.val;
        right.val = left.val;
        left.val = temp;
        changeNode(left.right,right.left);
        changeNode(left.left,right.right);
        }
       
    }
}

于是采用了如下方法

代码语言:javascript复制
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode invertTree(TreeNode root) {
        if(root==null||root.left==null&&root.right==null){
            return root;
        }
        TreeNode left = root.left;
        TreeNode right = root.right;
           root.right= invertTree(left);
          root.left=  invertTree(right);
 
        return root;
    }
}

0 人点赞