二叉树的DFS/BFS的递归/非递归形式

二叉树的遍历是二叉树的经典算法,方式有很多,对理解递归迭代和堆栈队列有帮助。
以下是我写的二叉树深度优先遍历(DFS)和广度优先遍历(BFS)的递归和非递归形式,并顺便介绍一下完全二叉树计算节点个数的算法。

1. BFS的递归形式

说到递归,大家一般都会想到DFS。但是递归跟DFS其实没有关系,只是我们常常习惯用DFS递归而已。二叉树的BFS就是以层序遍历二叉树的节点。这个思路就是,每当DFS遍历到一个新的节点,就把它加入到所在层的list里面去。其实是用DFS的方法实现了二叉树的BFS。下面的这个实现,把每层的node放置在一个子List里面。

    public List> traversal(TreeNode root) {
        if (root == null) {
            return null;
        }
        List> list = new ArrayList<>();
        dfs(root, 0, list);
        return list;
    }

    private void dfs(TreeNode root, int level, List> list) {
        if (root == null) {
            return;
        }
        if (level >= list.size()) {
            List subList = new ArrayList<>();
            subList.add(root);
            list.add(subList);
        } else {
            list.get(level).add(root);
        }
        dfs(root.left, level + 1, list);
        dfs(root.right, level + 1, list);
    }

2. BFS的非递归形式

BFS的非递归形式是我个人非常喜欢的一套写法,用了Queue的数据结构,并且维护当前层的node数量和下一层的node数量。

    public List traversal(TreeNode root) {
        if (root == null) {
            return null;
        }
        return bfs(root);
    }

    private List bfs(TreeNode root) {
        int curNum = 1;
        int nextNum = 0;
        Queue queue = new LinkedList<>();
        List res = new ArrayList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            res.add(node);
            curNum--;
            if (node.left != null) {
                queue.add(node.left);
                nextNum++;
            }

            if (node.right != null) {
                queue.add(node.right);
                nextNum++;
            }

            if (curNum == 0) {
                curNum = nextNum;
                nextNum = 0;
            }
        }
        return res;
    }

或者:

    public List Bfs_tree(TreeNode root){
        Queue myq = new LinkedList<>();
        List res = new ArrayList<>();
        if(root==null) return null;
        myq.add(root);
        while(!myq.isEmpty()){
            int len = myq.size();
            for(int i=0;i

3. DFS的递归形式

二叉树的DFS分为三种,preorder,inorder和postorder,这里以preorder为例,最经典的三行代码:

    List mRes = new ArrayList<>();

    public List traversal(TreeNode root) {
        dfs(root);
        return mRes;
    }

    private void dfs(TreeNode root) {
        if (root != null) {
            //preOrder
            mRes.add(root);
            dfs(root.left);
            dfs(root.right);
        }
    }

4. DFS的非递归形式

这是我之前不是很熟悉的一种形式。但我知道,它肯定是用栈模拟递归。至于怎么做,可以利用栈,现将右子树压栈再将左子树压栈:

    private List traversal(TreeNode root) {
        List res = new ArrayList<>();
        Stack stack = new Stack<>();
        stack.add(root);
        while (!stack.empty()) {
            TreeNode node = stack.peek();
            res.add(node);
            stack.pop();
            if (node.right != null) {
                stack.push(node.right);
            }
            if (node.left != null) {
                stack.push(node.left);
            }
        }
        return res;
    }

可以看出上面是preOrder,inOrder和postOrder的话把res.add(node);的位置移动一下就好了。

[BONUS] 计算完全二叉树的node个数

Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.

要计算完全二叉树的结点个数,用上面这些遍历方式,复杂度都是O(n)。但是既然有「完全二叉树」这个条件,那复杂度肯定可以更低。这里可以利用计算满二叉树的结点个数的公式:

n = 2^h - 1

其实一颗完全二叉树,它的左右子树必然有一棵是满二叉树。那么,就只需要判断一下,然后递归地去计算各个小的满二叉树的node个数了。

    int height(TreeNode root) {
        //这里最后算出来的高度比真正高度小1
        return root == null ? -1 : 1 + height(root.left);
    }

    public int countNodes(TreeNode root) {
        //h 是root的高度-1
        int rootHeight = height(root);
        if (rootHeight == -1) {
            return 0;
        }
        //right subtree的高度是root高度-2,说明最后一层的node没有蔓延到right subtree,
        // 说明right subtree是真实高度为rootHeight + 1 -2 = rootHeight - 1的 complete binary tree
        if (height(root.right) == rootHeight - 2) {
            return countNodes(root.left) + (1 << rootHeight - 1) - 1 + 1;//(2^h - 1,+1是算上rootNode)
        } else {
            return countNodes(root.right) + (1 << rootHeight);
        }
    }

或者再精简一些,可以写成:

    int height(TreeNode root) {
        return root == null ? -1 : 1 + height(root.left);
    }
    public int countNodes(TreeNode root) {
        int h = height(root);
        return h < 0 ? 0 :
               height(root.right) == h-1 ? (1 << h) + countNodes(root.right)
                                         : (1 << h-1) + countNodes(root.left);
    }

分析一下复杂度:递归执行了O(log(n))次(每次只选择半棵树),计算高度每次用了O(log(n))时间,所以总体是 O(log(n)^2).。

by DrunkPaino

你可能感兴趣的:(二叉树的DFS/BFS的递归/非递归形式)