94. Binary Tree Inorder Traversal
94. Binary Tree Inorder Traversal
Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree[1,null,2,3]
,1 \ 2 / 3
return
[1,3,2]
.
该题是做树的中序遍历,下面分别是递归解法和非递归解法:
递归解法:
class Solution(object): def inorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ if not root: return [] return self.inorderTraversal(root.left) + [root.val] + self.inorderTraversal(root.right)
非递归解法:
class Solution(object): def inorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ if not root: return [] stack = [] node = root result = [] while node or len(stack) > 0: while node: stack.append(node) node = node.left node = stack.pop() result.append(node.val) node = node.right return result