Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1
\
2
/
3
return [1,3,2]
.
Note: Recursive solution is trivial, could you do it iteratively?
题目大意:中序遍历一个二叉树,递归的方案太low,用迭代的方式来写?
解题思路:不用递归,那就自己实现栈呗
1、首先节点入栈,处理当前节点左孩子,并且压入栈,当左节点非空,循环遍历;
2、找到第一个左孩子为空的节点,将此节点出栈,将节点值加入结果链表,并把当前节点设为右孩子;
3、循环到栈为空。
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode curr = root;
while (curr != null || !stack.isEmpty()) {
while (curr != null) {
stack.add(curr);
curr = curr.left;
}
curr = stack.pop();
res.add(curr.val);
curr = curr.right;
}
return res;
}