码迷,mamicode.com
首页 > 其他好文 > 详细

二叉树的遍历

时间:2020-10-19 22:18:07      阅读:24      评论:0      收藏:0      [点我收藏+]

标签:先序遍历   中序遍历   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;
    }
}

后序遍历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;
        }
    }
}

二叉树的遍历

标签:先序遍历   中序遍历   null   res   二叉树的遍历   sys   后序   pop   ring   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!