Univalued Binary Tree - Tree - Easy - LeetCode
💻 coding

Univalued Binary Tree - Tree - Easy - LeetCode

1 min read 160 words
1 min read
ShareWhatsAppPost on X
  • 1A binary tree is univalued if all nodes share the same value, returning true if this condition is met.
  • 2Example inputs demonstrate that trees with differing values return false, while uniform trees return true.
  • 3The algorithm operates with a time complexity of O(n) and a space complexity of O(height).

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"A binary tree is univalued if all nodes share the same value, returning true if this condition is met."

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)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 9 October 2020 · 1 min read · 160 words

Part of AskGif Blog · coding

You might also like

Univalued Binary Tree - Tree - Easy - LeetCode | AskGif Blog