数据结构-树和二叉树-二叉树遍历

二叉树遍历

中序递归遍历:左子树,根,右子树

    private void inOrderTraverse(Node node) {
        if (node != null) {
            //遍历左子树
            this.inOrderTraverse(node.leftChild);
            //输出根的值
            System.out.print(node.value + " ");
            //遍历右子树
            this.inOrderTraverse(node.rightChild);
        }
    }

树的高度

    private int getHeight(Node node) {
        if (node == null) {
            return 0;
        }
        else {
            //获取左子树高度
            int lh = this.getHeight(node.leftChild);
            //获取右子树高度
            int rh = this.getHeight(node.rightChild);
            //返回
            return lh > rh ? lh + 1 : rh + 1;
        }
    }

树的结点数量

    private int size(Node node) {
        if (node == null) {
            return 0;
        }
        else {
            int lsize = this.size(node.leftChild);
            int rsize = this.size(node.rightChild);
            return lsize + rsize + 1;
        }
    }

树层次遍历:借助队列

public void levelOrderByStack() {
        if (root == null) return;
        Queue<Node> queue = new LinkedList<Node>();
        queue.add(root);
        while (queue.size() != 0){
            for (int i = 0; i < queue.size(); i++) {
                //取出当前队列中的结点
                Node temp = queue.poll();
                //打印一下结点的值
                System.out.print(temp.value+"--");
                //把该结点的左子树加到队列中
                if (temp.leftChild != null)
                    queue.add(temp.leftChild);
                //把右子树加到队列中
                if (temp.rightChild != null)
                    queue.add(temp.rightChild);
            }
        }
    }

中序遍历 非递归

public void inOrderByStack() {
        Deque<Node> stack = new LinkedList<>();
        Node current = root;
        while (current != null || !stack.isEmpty()){
            while (current != null){
                stack.push(current);
                current = current.leftChild;
            }
            if(!stack.isEmpty()){
                current = stack.pop();
                System.out.println(current.value+" ");
                current = current.rightChild;
            }
        }
    }
阅读 128

推荐阅读