首页 > 其他 > 详细

二叉树的遍历

时间:2020-10-19 09:43:11      阅读:26      评论:0      收藏:0      [点我收藏+]

先序遍历

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;
    }
}

后序遍历1

// 逆后序遍历
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() + " ");
}

后序遍历2

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;
        }
    }
}

二叉树的遍历

原文:https://www.cnblogs.com/Tchou/p/13837970.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!