思路:
DFS搜索会TLE。
DISCUSS中超简洁的一个方法,学习了。
递归的判断,如果一棵树沿着左子树一路下去和沿着右子树一路下去的路数相同(树高相同,都为H),则说明该数是满二叉树,可以用公式计算出节点个数2^H - 1
;如果路数不同(树高不同),则说明左右子树要分开算,就这样,一直递归下去分析。
c++ code:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int countNodes(TreeNode* root) {
if(root == NULL) return 0;
int lh = 0, rh = 0;
TreeNode *ltree = root, *rtree = root;
while(ltree != NULL) {
ltree = ltree->left;
lh++;
}
while(rtree != NULL) {
rtree = rtree->right;
rh++;
}
if(lh == rh) {
return (1<<lh) - 1;
}else {
return 1 + countNodes(root->left) + countNodes(root->right);
}
}
};
java code:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int countNodes(TreeNode root) {
if(root == null) return 0;
int ln = 0, rn = 0;
TreeNode lt = root, rt = root;
while(lt != null) {
lt = lt.left;
ln++;
}
while(rt != null) {
rt = rt.right;
rn++;
}
if(ln == rn) {
return (1<<ln) - 1;
}else {
return 1 + countNodes(root.left) + countNodes(root.right);
}
}
}