965. 单值二叉树
解法一
//时间复杂度O(n), 空间复杂度O(logn)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool check(TreeNode* root, const int val) {
if(!root) return true;
if(root->val != val || !check(root->left, val) || !check(root->right, val)) return false;
return true;
}
bool isUnivalTree(TreeNode* root) {
int rootVal = root->val;
return check(root, rootVal);
}
};
思路:
DFS。比较每一个节点是否等于根节点值。
2019/08/18 15:32