Given binary trees, write a function to check if they is equal or not.
The binary trees is considered equal if they is structurally identical and the nodes has the same value.
Test instructions: Judge whether the two trees are the same.
Ideas: One is recursion, one is to use the queue to do hierarchical traversal judgment.
/** * 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 && q = = null) return true; else if (P! = NULL && q = = null) return false; else if (p = = NULL && Q! = null) return false; else { if (p.val! = Q.val) return false; else return Issametree (P.left, Q.left) && issametree (P.right, q.right);}}}
/** * Definition for Binary tree * public class TreeNode {* int val, * TreeNode left, * TreeNode right; TreeNode (int x) {val = x;} *} */public class Solution {Private Boolean Issamenode (TreeNode p, TreeNode q) {if (P = = NULL && q = = null) return True;if ((P! = NULL && q = = null) | | (p = = NULL && Q! = null) | | (P.val! = q.val)) return False;return true;} public boolean issametree (TreeNode p, TreeNode q) {if (!issamenode (p, Q)) return false; if (p = = NULL && q = = null) return true; Linkedlist<treenode> left = new linkedlist<treenode> (); linkedlist<treenode> right = new linkedlist<treenode> (); Left.add (P); Right.add (q); while (Left.size ()! = 0 && right.size ()! = 0) {TreeNode ltmp = Left.peekfirst (); TreeNode rtmp = Right.peekfirst (); Left.removefirst (); Right.removefirst (); if (!issamenode (Ltmp.left, Rtmp.left)) return false; if (ltmp.left! = null &Amp;& Rtmp.left! = null) {Left.add (ltmp.left); Right.add (Rtmp.left); } if (!issamenode (Ltmp.right, Rtmp.right)) return false; if (ltmp.right! = NULL && rtmp.right! = null) {Left.add (ltmp.right); Right.add (Rtmp.right); }} return true; }}
Leetcode same Tree