Java 二叉树,深度优先遍历,广度优先遍历

 二叉树的深度优先遍历,可以使用栈,因为栈有后进先出的特性,

二叉树的广度优先遍历,可以使用队列来实现。

package sjjg;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Stack;

public class Tree1 {

    public static void main(String[] args) {

        int[] arr = {1,2,3,4,5,6,7};

        TreeNode root = createBinaryTree(arr, 0);

        getDFS(root);
        System.out.println();
        getBFS(root);

    }


    /**
     * 将一个数组,转为二叉树
     * 就是0 个为根,1个为根的左子树,2个为根的右子树,以此类推
     * 发现规律,对于二叉树,一个节点的左子树为index*2+1
     * 右子树为index*2+2
     */
    public static TreeNode createBinaryTree(int[] arr, int index){
        TreeNode node = null;
        if (index<arr.length){
            int value = arr[index];
            node = new TreeNode(value);
            node.left = createBinaryTree(arr,index*2+1);
            node.right = createBinaryTree(arr,index*2+2);
            return node;
        }
        return node;
    }

    /**
     * 深度优先遍历
     */
    public static void getDFS(TreeNode root){
        if (root == null) return;
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        TreeNode temp = null;
        while (!stack.isEmpty()){
            temp = stack.pop();
            System.out.print(temp.value+"\t");
            // 因为栈是先进后出的,所以先进右
            if (temp.right != null)
                stack.push(temp.right);
            if (temp.left != null)
                stack.push(temp.left);
        }
    }

    /**
     * 广度优先遍历
     */
    public static void getBFS(TreeNode root){
        if (root == null) return;
        Deque<TreeNode> queue = new ArrayDeque<>();
        queue.add(root);
        TreeNode temp = null;
        while (!queue.isEmpty()){
            temp = queue.remove();
            System.out.print(temp.value+"\t");
            if (temp.left != null)
                queue.add(temp.left);
            if (temp.right != null)
                queue.add(temp.right);
        }
    }

    static class TreeNode{
        int value;
        TreeNode left;
        TreeNode right;
        public TreeNode(int value) {
            this.value = value;
        }
    }

}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值