二叉树相关

二叉树

二叉树深度优先遍历(DFS)用栈

中序遍历(递归)

class TreeNode{
    TreeNode left;
    TreeNode right;
    int val;

    public TreeNode(int val) {
        this.val = val;
    }
}


public void infixOrder(TreeNode root){
	if(root != null) {
		System.out.println(root.val);
            infixOrder(root.left);
            infixOrder(root.right);
        }                    
    }    

中序遍历(非递归)

public void infixOrder(TreeNode root){
	Stack<TreeNode> stack = new Stack<>();
    if(root == null) return;
    while(root != null || !stack.isEmpty()){
    	while(root != null){//一直遍历直到左子树叶子节点
                stack.push(root);//根节点入栈
                root = root.left;
            }
		if(!stack.isEmpty()){
			root = stack.pop();//弹出左子树叶子节点
        	System.out.println(root.val);
        	root = root.right;
		}   
    }                
}    

前序遍历

前序遍历和中序唯一不同是输出的时机,前序根节点入栈即输出

public class preOrder {
    public void preOrder(TreeNode root){
        Stack<TreeNode> stack = new Stack<>();
        if(root == null) return;
        while(root != null || !stack.isEmpty()){
            while(root != null){//一直遍历直到左子树叶子节点
                stack.push(root);//根节点入栈
                System.out.println(root.val);
                root = root.left;
            }

            root = stack.pop();//弹出左子树叶子节点
            root = root.right;
        }
    }
}

后序遍历

与前、中序不同,有一个指针保存上一个访问过的节点

public void postOrder(TreeNode root){
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode pre = null;

        while(cur != null || !stack.isEmpty()){
            stack.push(cur);
            cur = cur.left;
        }

        cur = stack.peek();

        if(cur.right == null || cur.right == pre){
            cur = stack.pop();
            System.out.println(cur.val);
            pre = cur;
            cur = null;
        }else{
            cur = cur.right;
        }
    }

二叉树广度优先遍历(BFS)用队列

public void levelOrder(TreeNode root){
        Queue<TreeNode> queue = new LinkedList<>();
        if(root != null){
            queue.offer(root);
        }
        while (!queue.isEmpty()){
            int n = queue.size();//记录每层节点数,防止其他层节点入队影响本层节点输出
            for(int i = 0; i < n; i++){
                TreeNode node = queue.poll();//去除本层节点
                System.out.println(node.val);
                if(root.left != null) queue.offer(root.left);//下层左右节点入队
                if(root.right != null) queue.offer(root.right);
            }
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值