// 前序遍历
while(root != null || !stack.isEmpty()){
while(root != null){
res.add(root.val);
stack.push(root);
root = root.left;
}
TreeNode cur = stack.pop();
root = cur.right;
}
// 后序遍历
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;
}
Collections.reverse(res);
//中序遍历
while(root != null || !stack.isEmpty()){
while(root != null){
stack.push(root);
root = root.left;
}
root = stack.pop();
res.add(root.val);
root = root.right;
}
二叉树前中后序的非递归遍历
最新推荐文章于 2022-11-04 22:51:50 发布