leetcode-965 Univalued Binary Tree

965. Univalued Binary Tree

A binary tree is univalued if every node in the tree has the same value.

Return true if and only if the given tree is univalued.

Example 1:

1
2
Input: [1,1,1,1,1,null,1]
Output: true

Example 2:

1
2
Input: [2,2,2,5,2]
Output: false

Note:

  1. The number of nodes in the given tree will be in the range [1, 100].
  2. Each node’s value will be an integer in the range [0, 99].

Analyse

判断一棵树是不是所有节点的值都相同

层序遍历

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
bool isUnivalTree(TreeNode* root) {
int value = root->val;

queue<TreeNode*> que;
que.push(root);

while (!que.empty())
{
TreeNode* node = que.front();
que.pop();

if (node->val != value)
{
return false;
}
else
{
if (node->left)
{
que.push(node->left);
}

if (node->right)
{
que.push(node->right);
}
}
}

return true;
}

递归

分成两个子问题来判断,左子树和右子树是否是UnivalTree

1
2
3
4
5
6
bool isUnivalTree(TreeNode* root)
{
return (root->left == nullptr || (root->left->val == root->val && isUnivalTree(root->left)))
&&
(root->right == nullptr || (root->right->val == root->val && isUnivalTree(root->right)));
}