码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode-JAVA] Invert Binary Tree

时间:2015-06-20 13:10:12      阅读:429      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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;
    }
}

 

[LeetCode-JAVA] Invert Binary Tree

标签:

原文地址:http://www.cnblogs.com/TinyBobo/p/4590425.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!