LeetCode 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:

1100338-20190104092353405-1007685324.png

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

Example 2:

1100338-20190104092352591-1226199608.png

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].

题目描述:大概意思就是问我们给定一棵树,判断这棵树上的所有节点的值是不是相同的,相同即为 true ,不相同为 false

题目分析:判断一棵树的所有节点的值是不是相同的,可以分为以下几个条件:

  • 节点是否为空
  • 左子节点和父节点是否相同
  • 右子节点和父节点是否相同
  • 左子节点和右子节点是否相同

根据这个思路我们可以解决这个问题。

python 代码:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def isUnivalTree(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        left_correct = not root.left or root.val == root.left.val and self.isUnivalTree(root.left)
        right_correct = not root.right or root.val == root.right.val and self.isUnivalTree(root.right)
        return left_correct and right_correct

C++ 代码:

/**
 * 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:
    int temp;
    bool flag = true;
    
    bool isUnivalTree(TreeNode* root) {
        if(!root){
            return true;
        }
        temp = root->val;
        travelTree(root);
        return flag;    
    }
    
    void travelTree(TreeNode* root){
        if(root){
            travelTree(root->left);
            travelTree(root->right);
            if(flag){
                flag = root->val == temp ? true : false;
            }
        }
    }
    
};

转载于:https://www.cnblogs.com/ECJTUACM-873284962/p/10218026.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值