zoukankan      html  css  js  c++  java
  • 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)
  • 相关阅读:
    FlexGrid布局
    Grid 布局管理器
    StaticBox布局管理器
    鼠标事件
    screen 常用命令
    wxPython 安装 及参考文档
    wxPython 界面编程的有关事件
    关于用python作为第三方程序,来调用shell命令的问题,以及返回值格式解析
    Mysql的增删改查
    linux ubuntu 系统修改源
  • 原文地址:https://www.cnblogs.com/asenyang/p/9780149.html
Copyright © 2011-2022 走看看