zoukankan      html  css  js  c++  java
  • Python实现二叉树的非递归先序遍历

    思路:

    1. 使用列表保存结果;

    2. 使用栈(列表实现)存储结点;

    3. 当根结点存在,保存结果,根结点入栈;

    4. 将根结点指向左子树;

    5. 根结点不存在,栈顶元素出栈,并将根结点指向栈顶元素的右子树;

    6. 重复步骤3-6,直到栈空。

    LeetCode: 144. Binary Tree Preorder Traversal

    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def preorderTraversal(self, root):
            """
            :type root: TreeNode
            :rtype: List[int]
            """
            ret = []
            stack = []
            while root or stack:
                while root:
                    ret.append(root.val)
                    stack.append(root)
                    root = root.left
                if stack:
                    t = stack.pop()
                    root = t.right
            return ret
    
  • 相关阅读:
    浅谈最长上升子序列(LIS)
    浅谈树链剖分
    数字计数
    windy数
    骑士(树形dp)
    旅游规划
    皇宫看守
    k8s安装报错
    linux文件夹存储潜规则
    搭建覆盖率测试环境
  • 原文地址:https://www.cnblogs.com/qiaojushuang/p/7862930.html
Copyright © 2011-2022 走看看