美文网首页Leetcode
Leetcode 222. Count Complete Tre

Leetcode 222. Count Complete Tre

作者: SnailTyan | 来源:发表于2018-08-30 19:02 被阅读5次

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Count Complete Tree Nodes

2. Solution

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int countNodes(TreeNode* root) {
        if(!root) {
            return 0;
        }
        int leftDepth = 0;
        int rightDepth = 0;
        TreeNode* left = root;
        TreeNode* right = root;
        while(left) {
            leftDepth++;
            left = left->left; 
        }
        while(right) {
            rightDepth++;
            right = right->right; 
        }
        if(leftDepth == rightDepth) {
            return pow(2, leftDepth) - 1;
        }
        else {
            return 1 + countNodes(root->left) + countNodes(root->right);
        }
    }
};

Reference

  1. https://leetcode.com/problems/count-complete-tree-nodes/description/

相关文章

网友评论

    本文标题:Leetcode 222. Count Complete Tre

    本文链接:https://www.haomeiwen.com/subject/mnorwftx.html