Topic:
Given two binary trees, compare whether two binary trees are the same
Ideas:
Recursion.
Base case:
True if both trees are empty trees
If one is empty, false
General
Compare root nodes for equality before recursively comparing left and right subtrees
/**
* Same Tree
*
* Given binary trees, write a function to check if they is equal or not.
*
* binary trees is considered equal if they is structurally identical and * the nodes has the
same value.< c6/>*
*
/public class S100 {public
static void Main (string[] args) {
} public
Boolean Issametree ( TreeNode p, TreeNode q) {
//If both are empty, then equal if
(P==null && q==null) {
return true;
} else if (P==null | | q==null) { //If an empty one is not empty, the return is not equal to
false;
}
if (P.val = = q.val) { //If the node values are equal, continue to check the left and right subtree of p,q
return Issametree (P.left, Q.left) && Issametree (p.right , q.right);
} else{
return false;}}
}
/**
* Definition for binary Tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode (int x) {val = x;}
* *
/public class Solution {public
boolean issametree (TreeNode p, TreeNode q) {
if (p==null &&A mp Q==null) {
return true;
}
if (P==null | | q==null) {
return false;
}
if (p.val! = q.val) {
return false;
}
Return Issametree (P.left, Q.left) && issametree (P.right, q.right);
}
}