zoukankan      html  css  js  c++  java
  • [LeetCode-JAVA] Invert Binary Tree

    题目:

    Invert a binary tree.

         4
       /   
      2     7
     /    / 
    1   3 6   9

    to

         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 fuck off.

    题意:反转一个二叉树,加点题外话,很简单的一个题,不过有关于这道题的小故事,点击链接即可

    思路1:利用递归

    代码:

    public class Solution {
        public TreeNode invertTree(TreeNode root) {
            if(root == null || (root.left == null && root.right == null))
                return root;
            
            TreeNode temp = root.right;
            root.right = invertTree(root.left);
            root.left = invertTree(temp);
            
            return root;
        }
    }

    思路2:非递归,利用stack

    代码2:

    public class Solution {
        public TreeNode invertTree(TreeNode root) {
            if(root == null) return null; 
            Stack<TreeNode> stack = new Stack<TreeNode>();  
            stack.push(root);  
            
            while(!stack.isEmpty()){  
                TreeNode cur = stack.pop();
                TreeNode temp = cur.left;
                cur.left = cur.right;
                cur.right = temp; 
                
                if(cur.left != null) stack.push(cur.left);  
                if(cur.right != null) stack.push(cur.right);  
            }  
            return root;
        }
    }
  • 相关阅读:
    xhr
    原生js的博客
    webstorm调试Node的时候配置
    multiparty
    bluebird
    Nodejs+express+angularjs+mongodb
    mustache.js
    ModelProxy 前端接口配置建模框架
    浏览器跨域访问解决方案
    前端性能优化补充篇
  • 原文地址:https://www.cnblogs.com/TinyBobo/p/4590425.html
Copyright © 2011-2022 走看看