前序遍历核心块
while(root != null || !stack.isEmpty()){
//go left down to the ground
while(root != null){
res.add(root.val);
stack.push(root);
root = root.left;
}
//if we reach to the leaf, go back to the parent right, and repeat the go left down.
TreeNode cur = stack.pop();
root = cur.right;
}
中序遍历
while (root != null || !stack.isEmpty()) {
while (root != null) {
stack.push(root);
root = root.left;
}
root = stack.pop();
res.add(root.val);
root = root.right;
}
后序遍历
原本是左右跟的顺序 ,反过来就是根右左,和前序遍历的差别根左右就是压栈的延申方向,一个往左,一个往右,最后在翻转整个list集合拿到的就是后序遍历数组
while(root != null || !stack.isEmpty()){
while(root != null){
res.add(root.val);
stack.push(root);
root = root.right;
}
TreeNode cur = stack.pop();
root = cur.left;
}