程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> LeetCode222——Count Complete Tree Nodes

LeetCode222——Count Complete Tree Nodes

編輯:關於C++

Given a complete binary tree, count the number of nodes.

Definition of a complete binary tree from Wikipedia:

In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2hnodes inclusive at the last level h.

實現:
class Solution {
public:
int getHeight(TreeNode* root) {
int h = 0;
while (root) {
root = root->left;
h++;
}
return h;
}
int countNodes(TreeNode* root) {
if (!root) return 0;
int lh = getHeight(root->left);
int rh = getHeight(root->right);

if (lh == rh)
return pow(2, lh) + countNodes(root->right);
return pow(2, rh) + countNodes(root->left);
}
};

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved