码迷,mamicode.com
首页 > 其他好文 > 详细

[LintCode] Binary Tree Flipping

时间:2017-09-07 11:59:59      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:des   toggle   linked   time   example   ges   hang   win   dep   

Given a binary tree where all the right nodes are either leaf nodes with a sibling (a left node that shares the same parent node) or empty, flip it upside down and turn it into a tree where the original right nodes turned into left leaf nodes. Return the new root.

Example

Given a binary tree {1,2,3,4,5}

    1
   /   2   3
 / 4   5

return the root of the binary tree {4,5,2,#,#,3,1}.

   4
  /  5   2
    /    3   1  


Think Out Loud


For a given node n whose left child is not null, we do the following changes.

n.left.left = n.right;

n.left.right = n;

n.left = null;

n.right = null.

 

The new root after flipping is the leftmost node in the original tree.

We can solve this recursively bottom up. Solving it top down is more complicated because we need the top nodes to access 

the down nodes. Changing the top nodes makes this process a lot harder.

 

O(n) runtime, O(H) space, H is the max depth of the give binary tree.



[LintCode] Binary Tree Flipping

标签:des   toggle   linked   time   example   ges   hang   win   dep   

原文地址:http://www.cnblogs.com/lz87/p/7478954.html

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