zoukankan      html  css  js  c++  java
  • LeetCode OJ

    这题的提示中给出,linked list是原来二叉树的先序遍历。所以我用一个栈暂时存储每个节点的右子树(如果它有右子树的话),然后把左子树交换到右子树,左节点置为null,之后迭代下去,当遇到叶子节点时,从栈中pop出一个子树,再继续,直到遇到叶子节点且栈中为空。

    下面是AC代码:

     1  /**
     2      * Given a binary tree, flatten it to a linked list in-place.
     3      * If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
     4      * @param root
     5      */
     6     public void flatten(TreeNode root){
     7         if(root == null || root.left==null && root.right == null)
     8             return;
     9         //the stack is for the right children
    10         LinkedList<TreeNode> stack = new LinkedList<TreeNode>();
    11         TreeNode temp = root;
    12         while(true){
    13             if(temp.left!=null)
    14             {
    15                 if(temp.right!=null)
    16                     stack.push(temp.right);
    17                 temp.right = temp.left;
    18                 temp.left = null;
    19                 
    20             }
    21             if(temp.right != null)
    22                 temp = temp.right;
    23             if(temp.left == null && temp.right == null){
    24                 if(stack.isEmpty())
    25                     break;
    26                 temp.right = stack.pop();
    27                 temp = temp.right;
    28             }
    29         }
    30         
    31     }
    有问题可以和我联系,bettyting2010#163 dot com
  • 相关阅读:
    Servle生命周期
    Nginx反向代理
    redis
    java二分查找
    Redis集群的数据一致性
    springmvc中controller不要定义全局变量
    elasticsearch-6.7.1和kibana-oss-6.7.1的Linux安装
    centos7.0查看IP,Linux基本命令
    高并发ConcurrentHashMap 1.8的原理
    JS 循环 while for do while
  • 原文地址:https://www.cnblogs.com/echoht/p/3707959.html
Copyright © 2011-2022 走看看