二叉树练习题
1.965. 单值二叉树 - 力扣(LeetCode)
/**
* 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) {
if(root == NULL){
return true;
}
if(root->left){
if(root->val != root->left->val){
return false;
}
if(!isUnivalTree(root->left)){//判断左子树是否符合单值条件
return false;
}
}
if(root->right){
if(root->val != root->right->val){
return false;
}
if(!isUnivalTree(root->right)){//判断右子树是否符合单值条件
return false;
}
}
return true;
}
};