ð 222. å®å šäºåæ çèç¹äžªæ°
2022幎10æ10æ¥
- algorithm
ð 222. å®å šäºåæ çèç¹äžªæ°
éŸåºŠ: ð
é®é¢æè¿°
解æ³
/**
* Definition for a binary tree node.
* public 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 {
public int countNodes(TreeNode root) {
// æè·¯ïŒ
// éåœ - å©çš å®å
šäºåæ çç¹æ§
return mySol(root);
}
private int mySol(TreeNode root) {
// éåœç»æ¢æ¡ä»¶
if(root == null) {
return 0;
}
if(root.left == null) {
return 1;
}
// éè¿å·Šå³åæ æ é«ïŒå€æå°åºæ¯å·Šåæ æªæ»¡ è¿æ¯ å³åæ æªæ»¡
int left = getHeight(root.left);
int right = getHeight(root.right);
if(left == right) {
// å·Šåæ 满
return (1 << left) + mySol(root.right);
} else {
// å·Šåæ æªæ»¡ïŒå³åæ 䞺空
return (1 << right) + mySol(root.left);
}
}
private int getHeight(TreeNode root) {
// éåœç»æ¢æ¡ä»¶
if(root == null) {
return 0;
}
return getHeight(root.left) + 1; // åªéèŠçå·Šåæ çé«åºŠïŒå°±æ¯æ é«
}
}