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:

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

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

題目描述:大概意思就是問我們給定一棵樹,判斷這棵樹上的所有節點的值是不是相同的,相同即爲 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;
            }
        }
    }
    
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章