tag: 栈, 树, 哈希表
// 递归
public List<Integer> inorderTraversal1(TreeNode root) {
List<Integer> list = new LinkedList<>();
helper(root, list);
return list;
}
private void helper(TreeNode node, List<Integer> list) {
if (node == null) {
return;
}
if (node.left != null) {
helper(node.left, list);
}
list.add(node.val);
if (node.right != null) {
helper(node.right, list);
}
}
// 迭代
public List<Integer> inorderTraversal2(TreeNode root) {
List<Integer> list = new LinkedList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode curr = root;
while (curr != null || !stack.isEmpty()) {
while (curr != null) {
stack.push(curr);
curr = curr.left;
}
curr = stack.pop();
list.add(curr.val);
curr = curr.right;
}
return list;
}
网友评论