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