LeetCode 222. 完全二叉树节点个数(方法一)

题目描述链接:https://leetcode-cn.com/problems/count-complete-tree-nodes/

解题思路:方法一:递归。此种方法用不到完全二叉树的特性,故时间复杂度和空间复杂度均较高。

方法一:LeetCode C++求解代码如下:

/**
 * 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;
      }
      return 1+countNodes(root->left)+countNodes(root->right);
    }
};

            

原文地址:https://www.cnblogs.com/zzw-/p/13464637.html