• [LeetCode] 226. Invert Binary Tree(反转二叉树)


    • Difficulty: Easy

    • Related Topics: Tree

    Description

    Invert a binary tree.

    反转一棵二叉树

    Examples

    Example 1

    Input:

         4
       /   
      2     7
     /    / 
    1   3 6   9
    

    Output:

         4
       /   
      7     2
     /    / 
    9   6 3   1
    

    Trivia

    This problem was inspired by this original tweet by Max Howell:

    Google: 90% of our engineers use the software you wrote (Homebrew), but you can't invert a binary tree on a whiteboard so f*** off.

    Solution

    “不能在白板上反转一棵二叉树的都是 **?”那今天的题目就不开 IDE 做了,直接裸写代码,相关的解释都在注释里了,自己看吧。

    /**
     * Example:
     * var ti = TreeNode(5)
     * var v = ti.`val`
     * Definition for a binary tree node.
     * class TreeNode(var `val`: Int) {
     *     var left: TreeNode? = null
     *     var right: TreeNode? = null
     * }
     */
    class Solution {
        fun invertTree(root: TreeNode?): TreeNode? {
            if (root == null) {
                return root
            }
            // 节点的左右子树交换
            val t = root.left
            root.left = root.right
            root.right = t
            
            // 对左右子树进行递归交换
            root.left = invertTree(root.left)
            root.right = invertTree(root.right)
            
            return root
        }
    }
    
  • 相关阅读:
    《java网络编程》
    画类图的使用工具----转载
    桌面应用要素
    java桌面应用
    java网络程序
    网络程序
    java中的数据类型
    数据类型要素
    java中的设计模式
    输入一个年龄,判断年龄范围
  • 原文地址:https://www.cnblogs.com/zhongju/p/13780155.html
Copyright © 2020-2023  润新知