二叉树遍历

二叉树

二叉树是每个结点最多有两个子树的树结构,二叉树常被用于实现二叉查找树和二叉堆

定义树节点结构

private static class TreeNode<T>{
    T val;
    TreeNode left;
    TreeNode right;

    TreeNode(T val){
        this.val = val;
    }
}

创建二叉树

 public static TreeNode creatBinaryTree(LinkedList<T> list){
     TreeNode root = null;
     if(list == null || list.isEmpty()) {
         reutrn root;
     }
     T val = list.removeFirst();
     if(val != null) {
         root = new TreeNode(val);
         root.left = creatBinaryTree(list);
         root.right = creatBinaryTree(list);
     }
     return root;
 }

前序遍历

按照 根-左-右 顺序递归遍历

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

中序遍历

public void inOrder(TreeNode root) {
    if(root == null) {
        return;
    }
    preOrder(root.left);
    System.out.println(root.val);
    preOrder(root.right);
}

后序遍历

public void postOrder(TreeNode root) {
    if(root == null) {
        return;
    }        
    preOrder(root.left);
    preOrder(root.right);
    System.out.println(root.val);
}

二叉树遍历非递归实现

非递归使用最多的数据结构就是栈,栈具有先天的递归特性,以前序遍历为例:

public void preOrder(TreeNode root) {
    Stack<TreeNode> stack = new Stack<TreeNode>();
    TreeNode node = root;
    while(node != null || !stack.isEmpty()) {

        // 左孩子入栈
        while(node != null) {
            System.out.println(node.val);
            stack.push(node);
            node = node.left;
        }
        //左孩子为空, 弹出栈顶, 访问右孩子
        if(!stack.isEmpty()) {
            node = stack.pop();
            node = node.right;
        }
    }
}

二叉树的层序遍历

public void levelOrder(TreeNode root) {
    Queue<TreeNode> queue = new LinkedList<TreeNode>();
    queue.offer(root);
    while(!queue.isEmpty()) {
        
        TreeNode node = queue.poll();
        System.out.println(node.val);

        // 左孩子入队列
        if(node.left != null) {
            queue.offer(node.left);
        }    
        if(node.right != null) {
            queue.offer(node.right);
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值