Daily LeetCode 94. Binary Tree Inorder Traversal

https://leetcode.com/problems/binary-tree-inorder-traversal/

Medium

问题描述:

Given a binary tree, return the inorder traversal of its nodes’ values.

Example:

1
2
3
4
5
6
7
8
Input: [1,null,2,3]
1
\
2
/
3

Output: [1,3,2]

Follow up: Recursive solution is trivial, could you do it iteratively?

思路及代码:

这一题是要中序遍历二叉树

方法1:

采用递归的方式进行遍历

1
2
3
4
5
6
7
8
9
10
11
def inorderTraversal(root):
def traversal(root, res):
if root:
traversal(root.left, res)
res.append(root.val)
traversal(root.right, res)

res = []
traversal(root, res)

return res

方法2:

采用非递归的方式进行中序遍历

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
if not root:
return None

stack = []
res = []

while root or stack:
while root:
stack.append(root)
root = root.left
root = stack.pop()
res.append(root.val)
root = root.right

return res