废话不多说,直接上题目。真的应该算是比较简单的一道题目了,可我又是看了解析恍然大悟!!!
方法一:深度优先遍历
先深度优先遍历,将树的所有节点中的值放进一个容器中,后面再比较容器中的值是否相等。
/**
* 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 {
// 深度优先遍历
void deep(TreeNode* node, vector<int>& vec){
if(node == NULL) return;
vec.push_back(node->val);
deep(node->left, vec);
deep(node->right, vec);
}
public:
bool isUnivalTree(TreeNode* root) {
vector<int> vec;
deep(root, vec);
for(int i = 0; i < vec.size()-1; i++){
if(vec[i] != vec[i+1])
return false;
}
return true;
}
};
方法二:递归
怎么说呢,就一看就会,一做就废,还得练!继续坚持吧。
/**
* 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 isUnivalTree(TreeNode* root) {
// 递归
if(root == NULL) return true;
if(root->left != NULL && root->left->val != root->val)
return false;
if(root->right != NULL && root->right->val != root->val)
return false;
bool left_tree = isUnivalTree(root->left);
bool right_tree = isUnivalTree(root->right);
return left_tree && right_tree;
}
};
Keep learning! Keep moving!