二叉树的中序遍历
二叉树的先序遍历 | 二叉树的后序遍历 | 二叉树的层序遍历
cur == null 说明没有左子树(叶子节点)或者左子树已经完成遍历,可以开始遍历右子树了。 在我的另一篇文章《二叉树的后序遍历》所给出的版本二中有类似的用法。
public ArrayList<Integer> inorderTraversal(TreeNode root) {
TreeNode cur = root;
Stack<TreeNode> stack = new Stack<TreeNode>();
ArrayList<Integer> ans = new ArrayList<Integer>(20);
while (cur != null || !stack.isEmpty()) {
// 相当于一个开关
if (cur != null) {
stack.push(cur);
cur = cur.left;
}
else {
cur = stack.pop();
ans.add(cur.val);
if (cur.right == null) {
cur = null;
}
else {
cur = cur.right;
stack.push(cur);
cur = cur.left;
}
}
}
return ans;
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
this.val = x;
}
}