keep learning, keep coding!
Problem - Count Complete Tree Nodes
Given the root of a complete binary tree, return the number of the nodes in the tree.
According to Wikipedia, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.
Design an algorithm that runs in less than O(n) time complexity.
翻譯蒟蒻
給定一個完全二元樹的根節點,返回樹中節點的總數。Wikipedia 解釋完全二元樹是一種樹結構,其每一層(除了可能是最後一層)都是完全填滿的,而最後一層的所有節點都盡可能地靠左。在最後一層的高度為 h 時,最後一層的節點數介於 1 和 2^h(含)之間。這個問題要求設計時間複雜度不超過 O(n) 的演算法。意即:算法的執行時間應該隨著節點數量的增加而呈線性增長。
Example 1:
1
2Input: root = [1,2,3,4,5,6]
Output: 6Example 2:
1
2Input: root = []
Output: 0Example 3:
1
2Input: root = [1]
Output: 1
通過遞迴遍歷整個樹,計算並返回樹中的節點數量。
Solution - JavaScript
1 | /** |
Solution - Ruby
1 | def count_nodes(root) |
Solution - PHP
1 | function countNodes($root) { |