Leetcode solution 226. Invert Binary Tree

Posted baozitraining

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode solution 226. Invert Binary Tree相关的知识,希望对你有一定的参考价值。

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

以上是关于Leetcode solution 226. Invert Binary Tree的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode226翻转二叉树

Leetcode226:Invert Binary Tree

Python解Leetcode: 226. Invert Binary Tree

leetcode226 翻转二叉树(Easy)

[LeetCode226]Invert Binary Tree

LeetCode #226 翻转二叉树