中序遍历是先遍历左子树,在自身,再遍历右子树,

非递归实现的方法,一直遍历左节点,然后出栈,在遍历右节点

 

# 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 inorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        if root ==None:
            return []
        stack=[]
        result=[]
        while (len(stack)!=0 or  root!=None):
            while root!=None:
                stack.append(root)
                root =root.left
            if len(stack)!=0:
                root=stack.pop()
                result.append(root.val)
                root =root.right
        return result

 

相关文章:

  • 2022-12-23
  • 2021-12-10
  • 2021-08-26
  • 2021-12-03
  • 2022-12-23
  • 2021-12-27
  • 2021-07-31
  • 2021-04-24
猜你喜欢
  • 2022-12-23
  • 2021-11-21
  • 2022-12-23
  • 2022-02-08
  • 2022-01-24
  • 2022-02-13
  • 2021-11-07
相关资源
相似解决方案