Sunday, August 14, 2016

250. Count Univalue Subtrees

Note every leaf is a uni-value subtree. We can check from bottom to top. Check the left child subtree and then the right child subtree. If one of them is not a uni-value subtree, the root can't be a uni-value subtree. Must the root be a uni-value subtree when and only when both left and right child subtrees are uni-value subtree and the root value is equal to its children's value. It is very easy to make a mistake in line 23. If we do something like "helper(root->left) && helper(root->right)", then we probably miss checking the right subtree when the left subtree becomes false.

1:  /**  
2:   * Definition for a binary tree node.  
3:   * struct TreeNode {  
4:   *   int val;  
5:   *   TreeNode *left;  
6:   *   TreeNode *right;  
7:   *   TreeNode(int x) : val(x), left(NULL), right(NULL) {}  
8:   * };  
9:   */  
10:  class Solution {  
11:  private:  
12:    int res;  
13:  public:  
14:    int countUnivalSubtrees(TreeNode* root) {  
15:      res = 0;  
16:      helper(root);  
17:      return res;  
18:    }  
19:    bool helper(TreeNode *root) {  
20:      if (root == NULL) return true;  
21:      bool r1 = helper(root->left);  
22:      bool r2 = helper(root->right);  
23:      if (r1 && r2) {  
24:        if (root->left && root->left->val != root->val) return false;  
25:        if (root->right && root->right->val != root->val) return false;  
26:        res++;  
27:        return true;  
28:      } else {  
29:        return false;  
30:      }  
31:    }  
32:  };  

No comments:

Post a Comment