题目描述:
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?
题目大意:
非递归实现二叉树的中序遍历
解题思路:
使用栈(Stack)
伪代码如下(摘录自Wikipedia Tree_traversal):
iterativeInorder(node)
parentStack = empty stack
while (not parentStack.isEmpty() or node ≠ null)
if (node ≠ null)
parentStack.push(node)
node = node.left
else
node = parentStack.pop()
visit(node)
node = node.right
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):
p = root
stack = []
ans = []
while p or stack:
while p:
stack.append(p)
p = p.left
p = stack.pop()
ans.append(p.val)
p = p.right
return ans
本文链接:http://bookshadow.com/weblog/2015/01/19/leetcode-binary-tree-inorder-traversal/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。