题目:https://leetcode.cn/problems/univalued-binary-tree/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
/** * 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 { public: bool isUnivalTree(TreeNode* root) { // 1. root has two children if (root->left && root->right) { // 1.1 root value == left value == right value, step in right and left child if (root->val == root->left->val && root->left->val == root->right->val) { return(isUnivalTree(root->right) && isUnivalTree(root->left)); // 1.2 not an unival tree } else { return false; } // 2. root only has left child } else if (root->left) { // 2.1 root value == left value, step in left child if (root->val == root->left->val) { return isUnivalTree(root->left); // 2.2 not an unival tree } else { return false; } // 3. root only has right child } else if (root->right) { // 3.1 root value == right value, step in right child if (root->val == root->right->val) { return isUnivalTree(root->right); // 3.2 not an unival tree } else { return false; } } // 4. root has no child return true; } }; |