給你一棵 完全二叉樹 的根節點 root ,求出該樹的節點個數。
完全二叉樹 的定義如下:在完全二叉樹中,除了最底層節點可能沒填滿外,其餘每層節點數都達到最大值,並且最下面一層的節點都集中在該層最左邊的若干位置。若最底層爲第 h 層,則該層包含 1~ 2h 個節點。
示例 1:
輸入:root = [1,2,3,4,5,6]
輸出:6
示例 2:
輸入:root = []
輸出:0
示例 3:
輸入:root = [1]
輸出:1
提示:
樹中節點的數目範圍是[0, 5 * 104]
0 <= Node.val <= 5 * 104
題目數據保證輸入的樹是 完全二叉樹
進階:遍歷樹來統計節點是一種時間複雜度爲 O(n) 的簡單解決方案。你可以設計一個更快的算法嗎?
解法:前序遍歷
//leetcode submit region begin(Prohibit modification and deletion)
/**
* 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 {
int res = 1;
public int countNodes(TreeNode root) {
if(root==null){
return 0;
}
if(root.left!=null){
res++;
}
if(root.right!=null){
res++;
}
countNodes(root.right);
countNodes(root.left);
return res;
}
}
//leetcode submit region end(Prohibit modification and deletion)