Given two binary trees, write a function to check if they are equal or not.
“Two binary trees are considered equal if they are structurally identical and the nodes have the same value.”
Return
Example
Solution
It’s a simple traversal problem, We can traverse both the tree and verify if node having equal value or not.
Code
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
/** * Definition for binary tree * class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { * val = x; * left=null; * right=null; * } * } */ public class Solution { public int isSameTree(TreeNode A, TreeNode B) { if(A==null && B==null) return 1; if(A==null || B==null) return 0; if(A.val!=B.val) return 0; return isSameTree(A.left,B.left) & isSameTree(A.right,B.right); } } |
Output
We encourage you to write a comment if you have a better solution or having any doubt on the above topic.