zoukankan      html  css  js  c++  java
  • 【嘎】二叉树-226. 翻转二叉树

    题目:

    翻转一棵二叉树。

    示例:

    输入:

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

    4
    /
    7 2
    / /
    9 6 3 1

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/invert-binary-tree

    下面是错误的解答:

    class Solution {
        public TreeNode invertTree(TreeNode root) {
            TreeNode left = root.left;
            TreeNode right = root.right;
            
            if (left != null) {
                invertTree(left);
            }
            if (right != null) {
                invertTree(right);
            }
            if (left != null && right != null) {
                int leftval = left.val;
                int rightval = right.val;
                right.val = leftval;
                left.val = right.val;
            }
           return root;
        }
    }

    然后。。虽然知道是错的,但是想不出来怎么才是对的

        // 先序遍历,根左右 从上向下交换
        public TreeNode invertTree(TreeNode root) {
            if (root == null) return null;
            TreeNode rightnode = root.right;
            root.right = invertTree(root.left); // 交换左子树结果赋值给右子树,所以要先记录右子树
            root.left = invertTree(rightnode);
            return root;
        }
        // 中序遍历,左根右
        public TreeNode invertTree(TreeNode root) {
            if (root == null) return null;
            invertTree(root.left); // 递归找到左节点
            TreeNode rightnode = root.right;
            root.right = root.left;
            root.left = rightnode;
            // 递归找到右节点 继续交换:因为此时左右节点已经交换了,所以此时的右节点为root.left
            invertTree(root.left);
         return root; }
    // 后序遍历,左右根 从下向上交换 public TreeNode invertTree(TreeNode root) { if (root == null) return null; TreeNode leftnode = invertTree(root.left); TreeNode rightnode = invertTree(root.right); root.right = leftnode; root.left = rightnode; return root; }
    越努力越幸运~ 加油ヾ(◍°∇°◍)ノ゙
  • 相关阅读:
    完全卸载SQL Server 2008r2
    win7:你需要来自Administrators的权限才能对此文件进行修改的一个文件
    web.config文件中配置数据库连接的两种方式
    IIS6/7 配置操作
    IIS6/7 配置问题
    svn一整套使用,从下载到整个服务器搭建完成的详细说明
    HTTP协议详解
    深入理解String的关键点和方法
    将博客搬至CSDN
    对Java Web项目中路径的理解
  • 原文地址:https://www.cnblogs.com/utomboy/p/12698358.html
Copyright © 2011-2022 走看看