965. 单值二叉树 - 力扣(LeetCode) (leetcode-cn.com)
利用了二叉搜索树最小绝对值思想。定义了pre
class Solution {
TreeNode*pre=nullptr;
bool res=true;
public:
bool isUnivalTree(TreeNode* root) {
if(root==nullptr) return true;
fun(root);
return res;
}
void fun(TreeNode*root){
if(root==nullptr) return;
fun(root->left);
if(pre!=nullptr){
if(pre->val!=root->val) res=false;
}
pre=root;
fun(root->right);
}
};