您现在的位置是:首页 > 后台技术 > 数据结构与算法数据结构与算法

完全二叉树的节点个数(图文)

第十三双眼睛2023-12-04【数据结构与算法】人已围观

简介完全二叉树的节点个数
给你一棵 完全二叉树 的根节点 root ,求出该树的节点个数。

思路:利用深度优先遍历或者广度优先遍历,都可以统计出节点个数。深度优先遍历代码如下:
public static int method1(TreeNode root) {
    List<Integer> list = new ArrayList<>();
    test(root, list);
    return list.size();
}

public static void test(TreeNode node,List<Integer> list) {
    if (node == null) {
        return ;
    }
    list.add(node.val);
    test(node.left, list);
    test(node.right, list);
}

广度优先遍历代码如下:
public static int method2(TreeNode root) {
    if (root == null) {
        return 0;
    }
    int count = 0;
    Deque<TreeNode> queue = new LinkedList<TreeNode>();
    queue.offer(root);
    while (!queue.isEmpty()) {
        TreeNode tempNode = queue.poll();
        if (tempNode != null) {
            count ++;
            if (tempNode.left != null) {
                queue.offer(tempNode.left);
            }
            if (tempNode.right != null) {
                queue.offer(tempNode.right);
            }
        }
    }
    return count;
}

Tags:

很赞哦! ()

文章评论

    共有条评论来说两句吧...

    用户名:

    验证码:

本站推荐

站点信息

  • 网站名称:JavaStudy
  • 建站时间:2019-1-14
  • 网站程序:帝国CMS7.5
  • 文章统计242篇文章
  • 标签管理标签云
  • 统计数据百度统计
  • 微信公众号:扫描二维码,关注我们