Fork me on GitHub

【数据结构】算法 Count Complete Tree Nodes 完全二叉树的节点个数

Count Complete Tree Nodes 完全二叉树的节点个数

给一棵完全二叉树,求出树的节点个数。

输入:root = [1,2,3,4,5,6]
输出:6

思路

完全二叉树 简单来说,就是最下面一层的缺少叶子节点。

所以需要做的就是从root开始递归计算节点。

递归

 public int countNodes(TreeNode root) {
        if(root==null){return 0;}
        return countNodes(root.right)+countNodes(root.left)+1;
    }

非递归暂时不写

Tag

tree

posted @ 2021-06-16 11:18  WilliamCui  阅读(80)  评论(0编辑  收藏  举报