0
点赞
收藏
分享

微信扫一扫

牛客——二叉树

caoxingyu 2022-04-27 阅读 72
python

文章目录

1、二叉树的前序遍历

在这里插入图片描述
在这里插入图片描述

class Solution:
    def preorderTraversal(self , root: TreeNode) -> List[int]:
        # write code here
        res, tmp = [], []
        cur = root# 借助一个指针
        while cur or tmp:# 指针和tmp还不为none的时候
            while cur:
                res.append(cur.val)# res里把cur加进去
                tmp.append(cur)# tmp用来存储剩下的东西的
                cur = cur.left# 前序是根左右 所以先left 再right
            cur = tmp.pop()# 把根弹出去
            cur = cur.right
        return res

2、二叉树的中序遍历

在这里插入图片描述
在这里插入图片描述

class Solution:
    def inorderTraversal(self , root: TreeNode) -> List[int]:
        # write code here
        # 左根右
        def dfs(root):
            if not root:
                return
            dfs(root.left)
            res.append(root.val)
            dfs(root.right)
        res = []
        dfs(root)
        return res

上面那个要是递归深度太大了,就可以换下面这个

class Solution:
    def inorderTraversal(self , root: TreeNode) -> List[int]:
        # write code here
        ans = []
        cur = root
        while cur:
            if cur.left:
                pre = cur.left
                while pre.right and pre.right != cur:
                    pre = pre.right
                if pre.right:
                    pre.right = None
                    ans.append(cur.val)
                    cur = cur.right
                else:
                    pre.right = cur
                    cur = cur.left
            else:
                ans.append(cur.val)
                cur = cur.right
        return ans

3、二叉树的后序遍历

在这里插入图片描述

class Solution:
    def postorderTraversal(self , root: TreeNode) -> List[int]:
        # write code here
        # 左右根
        def dfs(root):
            if not root:
                return
            dfs(root.left)
            dfs(root.right)
            res.append(root.val)
            
 
        res = []
        dfs(root)
        return res

1、



1、



1、



1、



1、



1、



1、



1、



1、



1、



1、



1、



1、



1、



1、



1、



1、



举报

相关推荐

0 条评论