参考了这篇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