Leetcode226.翻转二叉树

题目描述

推荐一个好理解的答案:

    class Solution {
        public TreeNode invertTree(TreeNode root) {
            if (root == null) {
                return null;
            }
            /**
             * 类似于数组中两个数交换
             */
            TreeNode tmp = root.left;
            root.left = invertTree(root.right);
            root.right = invertTree(tmp);
            return root;
        }
    }

官方答案:

class Solution {
    public TreeNode invertTree(TreeNode root) {
        if(root==null){
            return null;
        }
       TreeNode left= invertTree(root.left); //这里容易写错,经常会认为:left翻转后应该赋值给right
       TreeNode right= invertTree(root.right);
        root.left=right;
        root.right=left;
        return root;
    }
}

完整调试代码:

        public TreeNode invertTree(TreeNode root) {
            if (root == null) {
                System.out.println("return null");
                return null;
            }
            /**
             * 类似于数组中两个数交换
             */
            TreeNode tmp = root.left;
            root.left = invertTree(root.right);
            root.right = invertTree(tmp);
            System.out.println("return value:" + root.val+"\n");
            return root;
        }

运行结果:

      4      
    /   \    
  2       7  
 / \     / \ 
1   3   6   9
return null
return null
return value:9

return null
return null
return value:6

return value:7

return null
return null
return value:3

return null
return null
return value:1

return value:2

return value:4

      4      
    /   \    
  7       2  
 / \     / \ 
9   6   3   1

Process finished with exit code 0

相关推荐

  1. LeetCode226.翻转

    2024-07-20 00:20:03       34 阅读
  2. Leetcode226.翻转

    2024-07-20 00:20:03       18 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-20 00:20:03       52 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-20 00:20:03       54 阅读
  3. 在Django里面运行非项目文件

    2024-07-20 00:20:03       45 阅读
  4. Python语言-面向对象

    2024-07-20 00:20:03       55 阅读

热门阅读

  1. QtService实现后台服务linux,windows

    2024-07-20 00:20:03       17 阅读
  2. wpf 启动文件的设置

    2024-07-20 00:20:03       15 阅读
  3. WPF中MVVM常用的框架

    2024-07-20 00:20:03       17 阅读
  4. 代码随想录算法训练营第三十四天

    2024-07-20 00:20:03       17 阅读
  5. ES6 数值的扩展(十八)

    2024-07-20 00:20:03       12 阅读
  6. 从零开始学习嵌入式----数据结构之链表

    2024-07-20 00:20:03       20 阅读