leetcode 222.Count Complete Tree Nodes
阿新 • • 發佈:2018-09-12
pub com code spa binary eno span return let
完全二叉樹是從左邊開始一點點填充節點的,因此需要計算所有的節點的個數。
則分別從左邊和右邊來進行傳遞的,當左右是完全二叉樹的時候,其節點個數就是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