直接遍历
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}*/
public class Solution {
public int nodeNum(TreeNode head) {
if (head == null){
return 0;
}
return 1 + nodeNum(head.left) + nodeNum(head.right);
}
}
使用满二叉树的性质
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}*/
public class Solution {
public int nodeNum(TreeNode head) {
if (head == null){
return 0;
}
int left = getHeight(head.left);
int right = getHeight(head.right);
if (left != right){
return (int)Math.pow(2, right) + nodeNum(head.left);
}
return (int)Math.pow(2, left) + nodeNum(head.right);
}
private int getHeight(TreeNode node){
TreeNode cur = node;
int res = 0;
while (cur != null){
cur = cur.left;
res++;
}
return res;
}
}