首页 > 代码库 > 156. Binary Tree Upside Down

156. Binary Tree Upside Down

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