zoukankan      html  css  js  c++  java
  • Flatten Binary Tree to Linked List

    Given a binary tree, flatten it to a linked list in-place.

    For example,
    Given

             1
            / 
           2   5
          /    
         3   4   6
    

    The flattened tree should look like:

       1
        
         2
          
           3
            
             4
              
               5
                
                 6

    middle题目,为遍历二叉树的变种。

    可以看到实际最后的linkedlist是一个前序遍历的结果,根连向左子树,左子树的最右结点连向右子树。

    思路一:利用stack进行先序遍历时,当前元素的后继为栈顶元素,要么是当前元素的母结点的右子树,当前元素为左子树的最右结点时,栈顶存的是该最右结点的后续结点。时间复杂度O(n),空间复杂度O(n),有说O(logn)质疑。代码如下:

    class Solution(object):
        def flatten(self, root):
            """
            :type root: TreeNode
            :rtype: void Do not return anything, modify root in-place instead.
            """
            if not root:
                return 
            
            self.flatten(root.left)
            self.flatten(root.right)
            if not root.left: return 
            tmp = root.right
            root.right = root.left
            p = root.left
            while p.right: p = p.right #寻找左子树的最右结点
            p.right = tmp
            root.left = None

    另外一种解法,递归调用,先flatten 左子树,之后是右子树,将根结点的右指针指向左子树,寻找左子树的最右结点,连向原来的右子树。时间复杂度O(n),空间复杂度O(logn)。代码如下:

    class Solution(object):
        def flatten(self, root):
            """
            :type root: TreeNode
            :rtype: void Do not return anything, modify root in-place instead.
            """
            if not root:
                return 
            
            self.flatten(root.left)
            self.flatten(root.right)
            if not root.left: return 
            tmp = root.right
            root.right = root.left
            p = root.left
            while p.right: p = p.right
            p.right = tmp
            root.left = None

    注意这题会在面试中拓展为中序排列,值得注意。

  • 相关阅读:
    Linux_9/ RAID & LVM
    Linux_8/ fdisk, xfs_quota, edquota
    Linux_7/(chattr, lsattr), (setfacl, getfacl),su
    Linux_6/ Vim, Shell(下),(at, crond), (SUID, SGID, SBIT)
    Linux_5/ Vim, Shell(上)
    Linux_4/ |, (>, 2>, &>, >>, 2>>)
    Map集合的遍历
    List集合三种遍历方法
    MySQL安装
    排序法
  • 原文地址:https://www.cnblogs.com/sherylwang/p/5479402.html
Copyright © 2011-2022 走看看