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:


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


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


Note:

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

这题就是简单的二叉树的遍历,非常基础,这里使用深度优先遍历解决

class UnivaluedBinaryTree : public Solution {
public:
    void Execute() {

    }
    bool dfs(TreeNode *parent, TreeNode *cur) {
        if (nullptr == cur) {
            return true;
        }
        if (nullptr != cur && cur->val != parent->val) {
            return false;
        }
        return dfs(cur, cur->left) && dfs(cur, cur->right);
    }
    bool isUnivalTree(TreeNode* root) {
        return dfs(root, root->left) && dfs(root, root->right);
    }
};
共 0 条回复
暂时没有人回复哦,赶紧抢沙发
发表新回复

作者

sryan
today is a good day