LeetCode 222. Count Complete Tree Nodes
阿新 • • 發佈:2022-06-01
LeetCode 222. Count Complete Tree Nodes (完全二叉樹的節點個數)
題目
連結
https://leetcode.cn/problems/count-complete-tree-nodes/
問題描述
給你一棵 完全二叉樹 的根節點 root ,求出該樹的節點個數。
完全二叉樹 的定義如下:在完全二叉樹中,除了最底層節點可能沒填滿外,其餘每層節點數都達到最大值,並且最下面一層的節點都集中在該層最左邊的若干位置。若最底層為第 h 層,則該層包含 1~ 2h 個節點。
示例
輸入:root = [1,2,3,4,5,6]
輸出:6
提示
樹中節點的數目範圍是[0, 5 * 104]
0 <= Node.val <= 5 * 104
題目資料保證輸入的樹是 完全二叉樹
思路
藉助完全二叉樹的性質解題。
如果左右子樹深度一樣,那麼左子樹一定是滿的,樹點數為左子樹(公式)+右子樹+根節點。
如果深度不一樣,那麼右子樹一定是滿的,答案為左子樹+右子樹(公式)+根節點。
複雜度分析
時間複雜度 O(logn2)
空間複雜度 O(1)
程式碼
Java
public int countNodes(TreeNode root) { if (root == null) { return 0; } int leftDepth = getDepth(root.left); int rightDepth = getDepth(root.right); if (leftDepth == rightDepth) { return (int) (Math.pow(2, leftDepth)) + countNodes(root.right); } else { return (int) (Math.pow(2, rightDepth)) + countNodes(root.left); } } public int getDepth(TreeNode root) { int depth = 0; while (root != null) { root = root.left; depth++; } return depth; }