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; }
    越努力越幸运~ 加油ヾ(◍°∇°◍)ノ゙
  • 相关阅读:
    activity 之间传递参数
    手动创建一个Activity,完成页面跳转(intent 无参数)
    C++中汉字字符串的截取
    android基础知识清单。
    更改远程仓库
    设计模式六大原则
    事件订阅代码
    Python Mac ssl.SSLError certificate verify failed (_ssl.c:833)
    Python库中常见的 __all__ 变量是干啥的
    Thrift的使用-Python
  • 原文地址:https://www.cnblogs.com/utomboy/p/12698358.html
Copyright © 2011-2022 走看看