题目:
Given a binary tree, return the inorder traversal of its nodes' values.
Example:
Follow up: Recursive solution is trivial, could you do it iteratively?
解题:
二叉树的中序遍历,可以用递归的方式
(关于中序遍历可以参考我的另一篇博客,详细介绍了中序,前序,后序的意思:点击打开链接)
# 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 []
return self.inorderTraversal(root.left)+[root.val]+self.inorderTraversal(root.right)
也可以用栈的方式:
# 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]
"""
cur = root
stack = []
result = []
while stack or cur:
if cur:
stack.append(cur)
cur = cur.left
else:
cur = stack.pop()
result.append(cur.val)
cur = cur.right
return result