标签:先序遍历 中序遍历 null res 二叉树的遍历 sys 后序 pop ring
Stack<TreeNode> stk = new Stack<>();
stk.push(root);
while (!stk.empty()) {
TreeNode cur = stk.pop();
if (cur != null) {
// visit cur
stk.push(cur.right);
stk.push(cur.left);
}
}
Stack<TreeNode> stk = new Stack<>();
TreeNode cur = root;
while (cur != null || !stk.empty()) {
if (cur != null) {
stk.push(cur);
cur = cur.left;
}
else {
cur = stk.pop();
// visit cur
cur = cur.right;
}
}
// 逆后序遍历
Stack<TreeNode> src = new Stack<>();
Stack<TreeNode> res = new Stack<>();
src.push(root);
while(!src.isEmpty()){
TreeNode p = src.pop();
res.push(p);
if(p.left != null){
src.push(p.left);
}
if(p.right != null){
src.push(p.right);
}
}
// res 存的结果就是逆后序遍历结果
while(!res.empty()) {
System.out.pringln(res.pop() + " ");
}
if(h != null){
Stack<TreeNode> stack = new Stack<>();
stack.push(h);
TreeNode c = null;
while(!stack.isEmpty()){
c = stack.peek();
if(c.left != null && h != c.left && h != c.right){
stack.push(c.left);
}else if(c.right != null && h != c.right){
stack.push(c.right);
}else{
System.out.print(stack.pop().value + " ");
h = c;
}
}
}
标签:先序遍历 中序遍历 null res 二叉树的遍历 sys 后序 pop ring
原文地址:https://www.cnblogs.com/Tchou/p/13837970.html