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

156. Binary Tree Upside Down

时间:2016-09-24 23:36:00      阅读:255      评论:0      收藏:0      [点我收藏+]

标签:

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.

For 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  


根据题给定的tree的特性,新生产的tree的所有左子树均为原树的右子树。那么我们只有一个stack来存左子树就好了,然后pop第一个值作为新树的root,stack的下一个设为a为root的右子树,如果a有右子树,则root左子树为a的右子树,依次类推直到stack为空。
注意要讲新树的左子树设为null,t.right.left =null; 不然会出现无限循环。
 
public TreeNode UpsideDownBinaryTree(TreeNode root) {
         if(root == null) return null;
         var stack = new Stack<TreeNode>();
        
         while(root != null)
         {
             stack.Push(root);
             root = root.left;
         }
         var sentinel = new TreeNode(-1);
         var t = stack.Pop();
         sentinel.left = t;
         while(stack.Count()>0)
         {
             
             var next = stack.Pop();
             if(next.right != null)
             {
                 t.left = next.right;
                 next.right = null;
             }
             
             t.right =next;
             t.right.left =null;
             t = t.right;
         }
         return sentinel.left;
    }

迭代的方法为

 public TreeNode UpsideDownBinaryTree(TreeNode root) {
         return DFS(root);
         
    }
    
    private TreeNode DFS(TreeNode root)
    {
        if(root == null || root.left == null)
        {
            return root;
        }
        else
        {
            var l = root.left;
            var r = root.right;
            var res = DFS(root.left);
            l.right =root;
            l.left = r;
            root.left = null;root.right = null;
            return res;
        }
    }

 

156. Binary Tree Upside Down

标签:

原文地址:http://www.cnblogs.com/renyualbert/p/5904290.html

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