zoukankan      html  css  js  c++  java
  • 226. Invert Binary Tree

    package LeetCode_226
    
    import java.util.*
    
    /**
     * 226. Invert Binary Tree
     * https://leetcode.com/problems/invert-binary-tree/description/
     *
     * Invert a binary tree.
     *
     * 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.
     * */
    
    class TreeNode(var `val`: Int) {
        var left: TreeNode? = null
        var right: TreeNode? = null
    }
    
    class Solution {
        fun invertTree(root: TreeNode?): TreeNode? {
            //method 1: bfs
            if (root==null){
                return root
            }
            val queue = LinkedList<TreeNode>()
            queue.offer(root)
            while (queue.isNotEmpty()){
                //invert level by level
                val cur = queue.pop()
                if (cur!=null){
                    val temp = cur.left
                    cur.left = cur.right
                    cur.right = temp
                }
                if (cur.left!=null){
                    queue.offer(cur.left)
                }
                if (cur.right!=null){
                    queue.offer(cur.right)
                }
            }
            return root
        }
    }
  • 相关阅读:
    Tomcat部署项目
    正则表达式
    文件的上传和下载
    实现扫码登陆
    onepill Android端
    部署SpringBoot到阿里云
    Gson
    HTML自动刷新页面
    Spring Data JPA根据属性名查询
    Spring Date JPA实现增删改查
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/12964800.html
Copyright © 2011-2022 走看看