LeetCode 965. Univalued Binary Tree
发布时间:2020-12-14 05:17:00 所属栏目:大数据 来源:网络整理
导读: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,null,1]Output: true Example 2: Input: [2,2,5,2]Output: false Note: The number of nodes
A binary tree is univalued if every node in the tree has the same value. Return Example 1: Input: [1,1,null,1] Output: true Example 2: Input: [2,2,5,2] Output: false Note:
题目描述:大概意思就是问我们给定一棵树,判断这棵树上的所有节点的值是不是相同的,相同即为 题目分析:判断一棵树的所有节点的值是不是相同的,可以分为以下几个条件:
根据这个思路我们可以解决这个问题。
# 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
/** * 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; } } } }; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |