题目:Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1 \ 2 / 3
return [1,3,2]
.
Note: Recursive solution is trivial, could you do it iteratively?
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
描述:二叉树的中序遍历,非递归
solution by python:
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return a list of integers
def inorderTraversal(self, root):
if root == None: return []
stk,ans = [],[]
p = root
while p!=None or len(stk)!=0:
if p == None:
ans.append(stk[-1].val)
p = stk.pop().right
else:
stk.append(p)
p = p.left
return ans