1. 程式人生 > >二叉樹深度優先遍歷(遞迴、非遞迴)、廣度優先遍歷、構建二叉樹

二叉樹深度優先遍歷(遞迴、非遞迴)、廣度優先遍歷、構建二叉樹

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);

    }
}