统计二叉树中节点的个数(DFS + BFS)

思路描述

DFS

1.我们将统计二叉树中节点个数的问题进行分解问题分解这种思路也是求解涉及二叉树递归中的一种大思路!!!):

1.1 将统计二叉树中节点的个数的问题分解为:统计其左子树节点个数+统计其右子树节点个数
1.2为了统计左右子树节点的个数那么我们必须首先要知道其左右子树节点的个数,即由此我们想到先需要利用二叉树后序遍历的大框架来解决问题.(可能在看下面代码实现时候会稍微疑惑一下下为什么是int count = leftCount + rightCount + 1;为什么要加一,原因很简单,因为我们在往上的过程中还需要将当前子树的根节点也计算到里面去,所以需要加一)

BFS

BFS理解较简单直接套用BFS模板,再维护一个int 类型的变量count用于记录二叉树中节点的个数即可

代码

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

class Solution {
    /**
     * Count the node of binary tree(BFS)
     *
     * @param root The root node of binary tree
     * @return int
     */
    private int countByBFS(TreeNode root) {
        int count = 0;
        if (root == null) {
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        count++;
        while (!queue.isEmpty()) {
            int curLeveSize = queue.size();
            for (int i = 0; i < curLeveSize; ++i) {
                TreeNode node = queue.poll();
                if (node.left != null) {
                    queue.add(node.left);
                    count++;
                }
                if (node.right != null) {
                    queue.add(node.right);
                    count++;
                }
            }
        }
        return count;
    }

    /**
     * Count the node of binary tree(DFS)
     *
     * @param root The root node of binary tree
     * @return int
     */
    private int countByDFS(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftCount = countByDFS(root.left);
        int rightCount = countByDFS(root.right);
        int count = leftCount + rightCount + 1;
        return count;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值