Leetcode solution 226. Invert Binary Tree

喜欢而已 提交于 2020-01-07 12:06:13

Problem Statement 

Invert a binary tree.

Example:

Input:

     4
   /   \
  2     7
 / \   / \
1   3 6   9

Output:

     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 f*** off.

 Problem link

Video Tutorial

You can find the detailed video tutorial here

Thought Process

Simple question on understanding about recursion. It could be solved using pre-order and post-order traversal style recursion. It can also be solved iteratively using a queue. Please refer to Leetcode official solution. It's very similar to "Binary Tree ZigZag Level Order Traversal". Remember a full binary tree max leaf is (N+1)/2 or ceiling of N/2

, that's the O(N) space complexity using a queue.

 

If you are like Max Howell, you can show off but I would still recommend to stay humble if you really want the job. Brillient jerks are rare (IMHO Linus Torvalds is one) but very productive, but not all companies would accept those culture (Netflix does but not others). Be strong and humble.

Solutions

 1 public TreeNode invertTree(TreeNode root) {
 2     return this.helper(root);
 3 }
 4 
 5 // post order
 6 private TreeNode helper(TreeNode root) {
 7     if (root == null) {
 8         return root;
 9     }
10 
11     TreeNode l = helper(root.left);
12     TreeNode r = helper(root.right);
13 
14     root.left = r;
15     root.right = l;
16 
17     return root;
18 }
19 
20 // Preorder
21 private TreeNode invertHelper(TreeNode root) {
22     if (root == null) {
23         return null;
24     }
25 
26     TreeNode temp = root.left;
27     root.left = root.right;
28     root.right = temp;
29 
30     this.invertHelper(root.left);
31     this.invertHelper(root.right);
32 
33     return root;
34 } 

Recursion (pre-order and post-order)

Time Complexity: O(N), where N is the total number of tree nodes

Space Complexity: O(1) Or O(lgN) if you count the recursion function stack

 

References

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!