1. 程式人生 > >[LeetCode] 222. Count Complete Tree Nodes

[LeetCode] 222. Count Complete Tree Nodes

Count Complete Tree Nodes

Given a complete binary tree, count the number of nodes.
Note:
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 2h nodes inclusive at the last level h.
Example:

Input:
1
/ \
2 3
/ \ /
4 5 6
Output: 6

解析

求完整二叉樹的節點個數,直接遞迴左右節點個數。分別找出以當前節點為根節點的左子樹和右子樹的高度並對比,如果相等,則說明是滿二叉樹,直接返回節點個數,如果不相等,則節點個數為左子樹的節點個數加上右子樹的節點個數再加1(根節點),其中左右子樹節點個數的計算可以使用遞迴來計算。

程式碼

class Solution {
public:
    int countNodes(TreeNode* root) {
        if(!root) return 0;
        TreeNode* leftnode = root->left
; TreeNode* rightnode = root->right; int lefth,righth; lefth = righth = 0; while(leftnode){ lefth ++; leftnode = leftnode->left; } while(rightnode){ righth ++; rightnode = rightnode->right; } if
(lefth == righth) return pow(2, lefth+1) -1; else return countNodes(root->left) + countNodes(root->right) +1; } };

參考

http://www.cnblogs.com/grandyang/p/4567827.html