leetcode题解-965-单值二叉树

题目

My way

dfs遍历

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
/**
* 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 {
private:
int val;
bool isUT = true;

void dfs(TreeNode* root)
{
if (!root || !isUT) return;

isUT = (val == root->val ? true : false);

dfs(root->left);
dfs(root->right);
}

public:
bool isUnivalTree(TreeNode* root)
{
val = root->val;

dfs(root);

return isUT;
}
};