题目:
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].
Note: Recursive solution is trivial, could you do it iteratively?
解答:
Recursive:
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
if (root == null) return result;
if (root.left == null && root.right == null) {
result.add(root.val);
return result;
}
//合并两个list,直接addAll就好啦
result.addAll(inorderTraversal(root.left));
result.add(root.val);
result.addAll(inorderTraversal(root.right));
return result;
}
Iteratively
//Iterative的方法很巧妙,当时想了很久也没做出来,所以这里标注一下
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode curt = root;
while (curt != null || !stack.isEmpty()) {
while (curt != null) {
stack.push(curt);
curt = curt.left;
}
curt = stack.pop();
list.add(curt.val);
curt = curt.right;
}
return list;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。