标签:nbsp str count for span bin int col 完全
完全二叉树是从左边开始一点点填充节点的,因此需要计算所有的节点的个数。
则分别从左边和右边来进行传递的,当左右是完全二叉树的时候,其节点个数就是pow(2,h)-1。
/** * 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) { int hleft=0, hright=0; TreeNode* pleft=root, *pright=root; while(pleft){ hleft++; pleft=pleft->left; } while(pright){ hright++; pright=pright->right; } if(hleft==hright) return pow(2,hleft)-1; return countNodes(root->left)+countNodes(root->right)+1; } };
leetcode 222.Count Complete Tree Nodes
标签:nbsp str count for span bin int col 完全
原文地址:https://www.cnblogs.com/newnoobbird/p/9631814.html