zoukankan      html  css  js  c++  java
  • 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;
            }
        }
  • 相关阅读:
    开源协议
    markdown 语法和工具
    mac 终端 使用ftp命令
    谷歌囧大了!安统镜卓5.0刷入遇到system.img系像找不到
    linux下vi命令大全
    python编码处理:unicode字节串转成中文 各种字符串举例说明
    优秀前端资源备忘录
    mousewheel滚轮事件
    bootstrap插件之Carousel
    初识Node.js
  • 原文地址:https://www.cnblogs.com/renyualbert/p/5904290.html
Copyright © 2011-2022 走看看