Leetcode

Leetcode 222. Count Complete Tre

2018-08-30  本文已影响5人  SnailTyan

文章作者: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/
上一篇下一篇

猜你喜欢

热点阅读