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
  • 相关阅读:
    Java IO流
    Java中Char和Byte的区别
    Java常用类
    View
    3 View
    View
    3 View
    3 View视图 URLconf
    2 Model层
    2 Model层-模型成员
  • 原文地址:https://www.cnblogs.com/vector11248/p/9695686.html
Copyright © 2011-2022 走看看