
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to check all values in the tree are same or not in Python
Suppose we have a binary tree, we have to check whether all nodes in the tree have the same values or not.
So, if the input is like
then the output will be True
To solve this, we will follow these steps −
Define a function solve() . This will take root, and val
if root is null, then
return True
if val is not defined, then
val := value of root
return true when value of root is same as val and solve(left of root, val) and solve(right of root, val) are also true
Let us see the following implementation to get better understanding −
Example
class TreeNode: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def solve(self, root, val=None): if not root: return True if val is None: val = root.val return root.val == val and self.solve(root.left, val) and self.solve(root.right, val) ob = Solution() root = TreeNode(5) root.left = TreeNode(5) root.right = TreeNode(5) root.left.left = TreeNode(5) root.left.right = TreeNode(5) print(ob.solve(root))
Input
root = TreeNode(5) root.left = TreeNode(5) root.right = TreeNode(5) root.left.left = TreeNode(5) root.left.right = TreeNode(5)
Output
True
- Related Articles
- Program to check whether all leaves are at same level or not in Python
- Program to check whether given tree is symmetric tree or not in Python
- Program to check all listed delivery operations are valid or not in Python
- Program to check all 1s are present one after another or not in Python
- Program to check number of global and local inversions are same or not in Python
- Program to check whether leaves sequences are same of two leaves or not in python
- Program to check whether a binary tree is complete or not in Python
- Program to check whether a binary tree is BST or not in Python
- Program to check whether all palindromic substrings are of odd length or not in Python
- C# program to check whether two sequences are the same or not
- Program to check whether we can color a tree where no adjacent nodes have the same color or not in python
- C Program to check if two strings are same or not
- Program to check whether one tree is subtree of other or not in Python
- How to check if all values in a vector are integer or not in R?
- Program to check whether parentheses are balanced or not in Python

Advertisements