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.
題意:給定兩顆二叉樹,判斷它們是否相同
解題思路:層次遍曆
代碼:
public class Solution { public boolean isSameTree(TreeNode p, TreeNode q) { boolean result = false; if(p == null && q == null){ return true; } if(p == null ||q == null){ return false; } Queue<TreeNode> pQueue = new LinkedList<TreeNode>(); Queue<TreeNode> qQueue = new LinkedList<TreeNode>(); pQueue.add(p); qQueue.add(q); while(!pQueue.isEmpty() && !qQueue.isEmpty()){ TreeNode tempP = pQueue.poll(); TreeNode tempQ = qQueue.poll(); if(tempP == null && tempQ == null){ result = true; } if(tempP == null || tempQ ==null){ result = false; } if(tempP.val != tempQ.val){ result = false; break; }else{ result = true; } if(tempP.left != null){ pQueue.add(tempP.left); } if(tempP.right != null){ pQueue.add(tempP.right); } if(tempQ.left != null){ qQueue.add(tempQ.left); } if(tempQ.right != null){ qQueue.add(tempQ.right); } if(pQueue.size() != qQueue.size()){ result = false; break; } } return result; }}