250. Count Univalue Subtrees (M)

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

Input: root = [5,1,5,5,5,null,5]
Output: 4

Example 2:

Input: root = []
Output: 0

Example 3:

Input: root = [5,5,5,5,5,null,5]
Output: 6

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了

你可能感兴趣的:(250. Count Univalue Subtrees (M))