Hello, reader ππ½ ! Welcome to day 68 of the series on Problem Solving. Through this series, I aim to pick up at least one question everyday and share my approach for solving it.
Today, I will be picking up LeetCode's daily challenge problem: 872. Leaf-Similar Trees.
π€ Problem Statement
Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a leaf value sequence*.*
Two binary trees are considered leaf-similar if their leaf value sequence is the same.
Return
true
if and only if the two given trees with head nodesroot1
androot2
are leaf-similar.E.g:
root1 = [3,5,1,6,2,9,8,null,null,7,4], root2 = [3,5,1,6,7,4,2,null,null,null,null,null,null,9,8]
=>true
root1 = [1,2,3], root2 = [1,3,2]
=>false
π¬ Thought Process - Generate and Equate List of Leaf Nodes
The most intuitive way to solve this problem is to separately traverse each tree and add the values of all the leaf nodes to a list.
Once the traversal of both the trees are complete, we can find if every leaf node in both the trees have the same values.
For both the trees, we add the lead nodes values to separate lists.
π©π½βπ» Solution - Generate and Equate List of Leaf Nodes
- Below is the code for the approach for generating the list of leaf nodes from both the trees and equating them.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean leafSimilar(TreeNode root1, TreeNode root2) {
List<Integer> leafValues1 = new ArrayList(),
leafValues2 = new ArrayList();
traverseNodes(root1, leafValues1);
traverseNodes(root2, leafValues2);
if(leafValues1.size() != leafValues2.size()) {
return false;
}
for(int i = 0; i < leafValues1.size(); i++) {
if(leafValues1.get(i) != leafValues2.get(i)) {
return false;
}
}
return true;
}
private void traverseNodes(TreeNode root,
List<Integer> leafValues)
{
if(root == null) return;
if(root.right == null && root.left == null) {
leafValues.add(root.val);
return;
}
traverseNodes(root.left, leafValues);
traverseNodes(root.right, leafValues);
}
}
Time Complexity: O(n + m)
- n = number of nodes in the tree 1
- m = number of nodes in the tree 2
Space Complexity: O(n + m)
- n = number of nodes in the tree 1
- m = number of nodes in the tree 2
=> space to store the leaf nodes in a list
- You can find the link to the GitHub repo for this question here: 872. Leaf-Similar Trees.
Conclusion
That's a wrap for today's problem. If you liked my explanation then please do drop a like/ comment. Also, please correct me if I've made any mistakes or if you want me to improve something!
Thank you for reading!