Leetcode: Same Tree

 
   
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.
 
   

 

 1 /**

 2  * Definition for binary tree

 3  * public class TreeNode {

 4  *     int val;

 5  *     TreeNode left;

 6  *     TreeNode right;

 7  *     TreeNode(int x) { val = x; }

 8  * }

 9  */

10 public class Solution {

11     public boolean isSameTree(TreeNode p, TreeNode q) {

12         if(p==null && q==null) return true;

13         if(p==null && q!=null) return false;

14         if(p!=null && q==null) return false;

15         if(p.val != q.val) return false;

16         return isSameTree(p.left, q.left)&&isSameTree(p.right, q.right);

17     }

18 }

 别人的方法:

Solution1: 未研究

 1 public class Solution {

 2     public boolean isSameTree(TreeNode p, TreeNode q) {

 3         // Start typing your Java solution below

 4         // DO NOT write main() function

 5         Queue<TreeNode> tree1 = new LinkedList<TreeNode>();

 6         Queue<TreeNode> tree2 = new LinkedList<TreeNode>();

 7         tree1.offer(p);

 8         tree2.offer(q);

 9 

10         while(tree1.peek()!=null || tree2.peek()!=null){

11             TreeNode t1 = tree1.poll();

12             TreeNode t2 = tree2.poll();

13             if(t1!=null && t2!=null && t1.val == t2.val && ((t1.left==null)==(t2.left==null)) &&((t1.right==null)==(t2.right==null))) {

14                 if(t1.left!=null){

15                     tree1.offer(t1.left);

16                     tree2.offer(t2.left);

17                 }

18                 if(t1.right!=null){

19                     tree1.offer(t1.right);

20                     tree2.offer(t2.right);

21                 }

22             }else

23                 return false;

24         }

25         return true;

26     }

27 }

Solution2: 未研究

 1 public class SameTree {

 2     public boolean isSameTree(TreeNode p, TreeNode q) {

 3         // Start typing your Java solution below

 4         // DO NOT write main() function

 5         if (p == null) {

 6             return q == null;

 7         }

 8         if (q == null) {

 9             return p == null;

10         }

11         if (p.val == q.val) {

12             return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);

13         } else {

14             return false;

15         }

16     }

17 

18 }

 

你可能感兴趣的:(LeetCode)