zoukankan      html  css  js  c++  java
  • Leetcode 94 Binary Tree Inorder

    参考了这篇https://zxi.mytechroad.com/blog/tree/leetcode-94-binary-tree-inorder-traversal/

    用到一个栈

    cur = root ,cur初始指向根root

    while 循环条件,只要cur不指向空,&& 栈不为空

      cur 一路向左孩子指到底,并且压栈

      到底了,弹出栈顶,将栈顶元素压入 res结果集即可。

      再去指弹出元素的右孩子。

      重复上述,只不过不是用递归的做法。用while循环来控制

    代码

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution:
        def inorderTraversal(self, root):
            """
            :type root: TreeNode
            :rtype: List[int]
            """
            if root is None:
                return []
            res = []
            stack = []
            cur = root
            while cur is not None or len(stack)>0:
                while cur is not None:
                    stack.append(cur)
                    cur = cur.left
                temp = stack.pop()
                res.append(temp.val)
                cur = temp
                cur = cur.right
            return res
  • 相关阅读:
    工具类官网Web原型制作分享-Adobe
    还在为黑白网页设计犯难?12款设计帮你轻松解决!!!
    联系我们吧
    单调栈&&单调队列
    *模板--数据结构
    非递归线段树专题
    反素数
    线段树专题训练
    BST
    排列与组合
  • 原文地址:https://www.cnblogs.com/vector11248/p/9695686.html
Copyright © 2011-2022 走看看