https://leetcode.com/problems/univalued-binary-tree/

1. Use recursion

  1. //0 ms 8.6 MB
  2. /**
  3. * Definition for a binary tree node.
  4. * struct TreeNode {
  5. * int val;
  6. * TreeNode *left;
  7. * TreeNode *right;
  8. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  9. * };
  10. */
  11. class Solution {
  12. public:
  13. bool isUnivalTree(TreeNode* root) {
  14. if(!root) return true;
  15. bool unival = true;
  16. if( (root->left && root->val != root->left->val) ||
  17. (root->right && root->val != root->right->val) )
  18. unival = false;
  19. return unival && isUnivalTree(root->left) && isUnivalTree(root->right);
  20. }
  21. };