LeetCode – Invert Binary Tree (Java)
Java Solution 1 - Recursive
public TreeNode invertTree(TreeNode root) { helper(root); return root; } public void helper(TreeNode n){ if(n==null){ return; } TreeNode t = n.left; n.left = n.right; n.right = t; helper(n.left); helper(n.right); } |
The helper method is not necessary, and the recursive approach can be simplified as the following:
public TreeNode invertTree(TreeNode root) { if(root==null){ return root; } invertTree(root.left); invertTree(root.right); TreeNode t = root.left; root.left = root.right; root.right = t; return root; } |
Java Solution 2 - Iterative
public TreeNode invertTree(TreeNode root) { LinkedList<TreeNode> queue = new LinkedList<TreeNode>(); if(root!=null){ queue.add(root); } while(!queue.isEmpty()){ TreeNode p = queue.poll(); if(p.left!=null) queue.add(p.left); if(p.right!=null) queue.add(p.right); TreeNode temp = p.left; p.left = p.right; p.right = temp; } return root; } |
<pre><code> String foo = "bar"; </code></pre>
-
Ali
-
Chungho Song
-
Florian Courtial
-
Carlos Sousa
-
Kai LI
-
Theja
-
Wolv
-
Roi
-
Shailesh Agarwal