二叉树深度优先遍历(递归、非递归)、广度优先遍历、构建二叉树

public class BinaryTree {
    static class TreeNode{
        int value;
        TreeNode left;
        TreeNode right;
        public TreeNode(int value){
            this.value = value;
        }
    }
    TreeNode root;
    public BinaryTree(int []array){
        root = createBinaryTree(array,0);
    }
    //利用二叉树的数组表示法构建二叉树,并返回根节点。
    public  TreeNode createBinaryTree(int []array,int index){
        if (index < array.length){
            int value = array[index];
            TreeNode root = new TreeNode(value);
            root.left = createBinaryTree(array,index*2+1);
            root.right = createBinaryTree(array,index*2+2);
            return root;
        }
        return null;
    }
    //深度优先遍历的非递归实现,采用栈。
    public  void depthOrderTraversal(TreeNode root){
        if (root == null){
            System.out.println("空树!");
        }
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()){
            TreeNode node = stack.pop();
            System.out.println(node.value);
            //先让右结点入栈,以致在pop时确保左结点先出栈
            if (node.right != null){
                stack.push(node.right);
            }
            if (node.left != null){
                stack.push(node.left);
            }
        }
    }
    //深度优先遍历的递归实现
    public  void depthOrderTraversalWithRecursion(TreeNode root){
        if (root != null){
            System.out.println(root.value);
        }
        depthOrderTraversal(root.left);
        depthOrderTraversal(root.right);
    }

    //广度优先遍历的非递归实现。采用队列实现。广度优先遍历无法用递归实现
    public void breadthOrderTraversal(TreeNode root){
        if (root == null){
            System.out.println("空树!");
        }
        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.add(root);
        while (!queue.isEmpty()){
            TreeNode node = queue.remove();
            System.out.println(node.value);
            if (node.left != null){
                queue.add(node.left);
            }
            if (node.right != null){
                queue.add(node.right);
            }
        }
    }

    public static void main(String[] args) {
        int []array = {1,2,3,4,5,6,7};
        BinaryTree binaryTree = new BinaryTree(array);
//        binaryTree.depthOrderTraversal(binaryTree.root);
//        binaryTree.depthOrderTraversalWithRecursion(binaryTree.root);
        binaryTree.breadthOrderTraversal(binaryTree.root);

    }
}

 

  • 6
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值