Leetcode 222.完全二叉樹的節點個數
阿新 • • 發佈:2018-12-31
二叉樹 位運算 roo aid etl lin left lse public
完全二叉樹的節點個數
給出一個完全二叉樹,求出該樹的節點個數。
說明:
完全二叉樹的定義如下:在完全二叉樹中,除了最底層節點可能沒填滿外,其余每層節點數都達到最大值,並且最下面一層的節點都集中在該層最左邊的若幹位置。若最底層為第 h 層,則該層包含 1~ 2h 個節點。
示例:
輸入:
1
/ \
2 3
/ \ /
4 5 6
輸出: 6
1 public class Solution { 2 3 // 獲取左子樹的高度(其實是最左側分支) 4 public int getLeftHeight(TreeNode root) { 5 intcount = 0; 6 while (root != null) { 7 count++; 8 root = root.left; 9 } 10 return count; 11 } 12 13 // 獲取右子樹的高度(其實是最右側分支的高度) 14 public int getRightHeight(TreeNode root) { 15 int count = 0; 16 while (root != null) { 17 count++;18 root = root.right; 19 } 20 return count; 21 } 22 23 public int countNodes(TreeNode root) { 24 if (root == null) { 25 return 0; 26 } 27 int leftHeight = getLeftHeight(root); 28 int rightHeight = getRightHeight(root); 2930 if (leftHeight == rightHeight) { 31 // 表示是滿二叉樹,二叉樹的節點數直接由公式2^n-1得到 32 // leftHeight即為層數, 1 << leftHeight使用位運算計算2^leftHeight,效率更高 33 // 註意(1 << leftHeight) - 1 的括號必須有!! 34 return (1 << leftHeight) - 1; 35 } else { 36 // 若該二叉樹不是滿二叉樹,遞歸的調用該方法,計算左子樹和右子樹的節點數 37 return countNodes(root.left) + countNodes(root.right) + 1; 38 } 39 } 40 }
Leetcode 222.完全二叉樹的節點個數