Blogs Hub

by Sumit Chourasia | Oct 09, 2020 | Category :coding | Tags : algorithm binary-tree data-structure easy leetcode tree

Univalued Binary Tree - Tree - Easy - LeetCode

Univalued Binary Tree - Tree - Easy - LeetCode

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

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
public class Solution {
    public bool IsUnivalTree(TreeNode root) {        
        return Helper(root,null);
    }
    
    private bool Helper(TreeNode root,TreeNode parent){
        if(root == null){
            return true;
        }
        
        if(parent!=null && root.val != parent.val){
            return false;  
        }
                
        return Helper(root.left,root) && Helper(root.right,root);
    }
}

Time Complexity: O(n)

Space Complexity: O(height)

Contributed By: Sumit Chourasia
3Sum Closest - Array - Medium - LeetCode
Contributed By: Sumit Chourasia
Subsets - Array - Medium - LeetCode
Contributed By: Sumit Chourasia
Array Nesting - Array - Medium - LeetCode
Contributed By: Sumit Chourasia
Find the Highest Altitude - Array - Easy - LeetCode