• leetcode114


    class Solution {
    public:
        void flatten(TreeNode* root) {
            while(root){
                if(root->left){
                    TreeNode* pre=root->left;
                    while(pre->right){
                        pre=pre->right;
                        
                    }
                    pre->right=root->right;
                    root->right=root->left;
                    root->left=nullptr;
                }
                root=root->right;
            }
        }
    };

     补充一个DFS遍历,然后倒叙组装成类似链表的解决方案,使用python实现:

    class Solution:    
        def preOrder(self,root,l):
            if root != None:
                l.append(root)
    
                self.preOrder(root.left,l)
                self.preOrder(root.right,l)
    
        def flatten(self, root: 'TreeNode') -> 'None':
            if root == None:
                return
            l = list()
            self.preOrder(root,l)
            root = l[len(l)-1]
            for i in range(len(l)-2,-1,-1):
                l[i].left = None
                l[i].right = root
                root = l[i]

    python的递归实现:

     1 class Solution:
     2     def build(self,root):
     3         if root != None:
     4             if root.left != None and root.right != None:
     5                 right = self.build(root.right)#重建右子树
     6                 left = self.build(root.left)#重建左子树
     7                 leaf = left
     8                 while leaf.right != None:#找到左子树的叶子节点
     9                     leaf = leaf.right
    10                 leaf.right = right#右子树连接到左子树的末尾
    11                 root.right = left#根节点修改右子树
    12                 root.left = None#根结点左子树设为空
    13                 return root
    14             elif root.left != None and root.right == None:
    15                 root.right = self.build(root.left)
    16                 root.left = None
    17                 return root
    18             elif root.left == None and root.right != None:
    19                 root.right = self.build(root.right)
    20                 return root
    21             else:
    22                 return root
    23         return None
    24     
    25     def flatten(self, root: TreeNode) -> None:
    26         """
    27         Do not return anything, modify root in-place instead.
    28         """
    29         self.build(root)
  • 相关阅读:
    Java 实现常见内排序
    markdown基本语法
    HashMap (JDK1.8) 分析
    jQuery总结
    JS 数组 常用方法
    CSS样式 解决文字过长显示省略号问题
    Python中的 __name__属性的含义和作用
    http协议详细介绍
    Http和Https的区别
    爬虫——requests库使用方法
  • 原文地址:https://www.cnblogs.com/asenyang/p/9780149.html
Copyright © 2020-2023  润新知