您的位置:首页 > 其它

LeetCode题解:Same Tree

2015-08-28 10:24 267 查看
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;
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: