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
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 nodes root1 and root2 are leaf-similar.Example:
Input: root1={1,3,3}, root2={2,3,3}
Output: trueApproach
Java
import java.util.ArrayList;import java.util.List;public class LeafSimilarTrees {public static void main(String[] args) {TreeNode root1 = new TreeNode(1);root1.left = new TreeNode(3);root1.right = new TreeNode(3);TreeNode root2 = new TreeNode(2);root2.left = new TreeNode(3);root2.right = new TreeNode(3);System.out.println(leafSimilar(root1, root2));}static List<Integer> res1;static List<Integer> res2;static void leafnodes(TreeNode root, List<Integer> res) {// base case if tree is emptyif (root == null)return;// if leaf nodeif (root.left == null && root.right == null) {res.add(root.val);return;}// call for left subtreeif (root.left != null)leafnodes(root.left, res);// call for right subtreeif (root.right != null)leafnodes(root.right, res);}static boolean leafSimilar(TreeNode root1, TreeNode root2) {res1 = new ArrayList<Integer>();res2 = new ArrayList<Integer>();if (root1 == null && root2 == null)return true;if (root1 == null || root2 == null)return false;leafnodes(root1, res1);leafnodes(root2, res2);if (res1.size() != res2.size())return false;for (int i = 0; i < res1.size(); i++)if (res1.get(i) != res2.get(i))return false;return true;}}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;}}
C++
#include <bits/stdc++.h>using namespace std;//struct for treenodestruct TreeNode{int data;TreeNode *left;TreeNode *right;TreeNode(int data){this->data=data;this->left=NULL;this->right=NULL;}};vector<int> res1,res2;void leafnodes(TreeNode *root,vector<int> &res){//base case if tree is emptyif(root==NULL)return;//if leaf nodeif(root->left==NULL && root->right==NULL){res.push_back(root->data);return ;}//call for left subtreeif(root->left)leafnodes(root->left,res);//call for right subtreeif(root->right)leafnodes(root->right,res);}bool leafSimilar(TreeNode* root1, TreeNode* root2){if(root1==NULL&& root2==NULL)return true;if(root1==NULL||root2==NULL)return false;leafnodes(root1,res1);leafnodes(root2,res2);if(res1.size()!=res2.size())return false;for(int i=0;i<res1.size();i++)if(res1[i]!=res2[i])return false;return true;}int main(){TreeNode *root1=new TreeNode(1);root1->left=new TreeNode(3);root1->right=new TreeNode(3);TreeNode *root2=new TreeNode(2);root2->left=new TreeNode(3);root2->right=new TreeNode(3);if(leafSimilar(root1,root2))cout<<"true";elsecout<<"false";return 0;}
No comments:
Post a Comment