Given the root
of a binary tree, return the number of uni-value subtrees.
A uni-value subtree means all nodes of the subtree have the same value.
Example 1:
image<pre style="box-sizing: border-box; font-family: SFMono-Regular, Consolas, "Liberation Mono", Menlo, Courier, monospace; font-size: 13px; margin-top: 0px; margin-bottom: 1em; overflow: auto; background: var(--dark-bg); border-color: rgb(51, 51, 51); color: var(--font) !important; padding: 10px 15px; line-height: 1.6; border-radius: 3px; white-space: pre-wrap;">Input: root = [5,1,5,5,5,null,5]
Output: 4
</pre>
Example 2:
<pre style="box-sizing: border-box; font-family: SFMono-Regular, Consolas, "Liberation Mono", Menlo, Courier, monospace; font-size: 13px; margin-top: 0px; margin-bottom: 1em; overflow: auto; background: var(--dark-bg); border-color: rgb(51, 51, 51); color: var(--font) !important; padding: 10px 15px; line-height: 1.6; border-radius: 3px; white-space: pre-wrap;">Input: root = []
Output: 0
</pre>
Example 3:
<pre style="box-sizing: border-box; font-family: SFMono-Regular, Consolas, "Liberation Mono", Menlo, Courier, monospace; font-size: 13px; margin-top: 0px; margin-bottom: 1em; overflow: auto; background: var(--dark-bg); border-color: rgb(51, 51, 51); color: var(--font) !important; padding: 10px 15px; line-height: 1.6; border-radius: 3px; white-space: pre-wrap;">Input: root = [5,5,5,5,5,null,5]
Output: 6
</pre>
Constraints:
- The numbrt of the node in the tree will be in the range
[0, 1000]
. -1000 <= Node.val <= 1000
我的答案:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
private:
int count = 0;
public:
int countUnivalSubtrees(TreeNode* root) {
PostOrderTraverse(root);
return count;
}
bool PostOrderTraverse(TreeNode* root) {
if (root == nullptr)
return true;
// cout << root->val << endl;
bool univ_left = PostOrderTraverse(root->left);
bool univ_right = PostOrderTraverse(root->right);
if (univ_left and univ_right) {
int left_val = (root->left != nullptr)? root->left->val : root->val;
int right_val = (root->right != nullptr)? root->right->val : root->val;
if (root->val == left_val and root->val == right_val) {
++count;
return true;
}
}
return false;
}
};
Runtime: 4 ms, faster than 91.01% of C++ online submissions for Count Univalue Subtrees.
Memory Usage: 16.8 MB, less than 74.00% of C++ online submissions for Count Univalue Subtrees.
几个小问题:
- Ternery的问号又忘写了
- root 是nullptr不需要++count,只需要return true
- 不能吧
bool univ_left = PostOrderTraverse(root->left);
bool univ_right = PostOrderTraverse(root->right);
if (univ_left and univ_right)
写在一行里,否则left是false就不探索right了
网友评论