您的位置 首页 JAVA(2017)

100. 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.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        
        if(q == null && p == null) return true;
        if(!checks(p,q)) return false;
        Queue<TreeNode> nodesp = new LinkedList<TreeNode>();
        nodesp.add(p);
        Queue<TreeNode> nodesq = new LinkedList<TreeNode>();
        nodesq.add(q);        
        while(!nodesp.isEmpty()){
            int n = nodesp.size();
            while(n>0){
                TreeNode currp = nodesp.poll();
                TreeNode currq = nodesq.poll();
                if(currq.val != currp.val) return false;
                if(!checks(currq.right,currp.right)) return false;
                if(!checks(currq.left,currp.left)) return false;
                if(currp.left != null){
                    nodesp.add(currp.left);
                    nodesq.add(currq.left);
                }
                if(currp.right != null){
                    nodesp.add(currp.right);
                    nodesq.add(currq.right);
                }
                n--;
            }
            
        }
        return true;
    }
    public boolean checks(TreeNode p, TreeNode q){
        if(q == null && p == null) return true;
        if((q ==null && p != null) || (p ==null && q != null)) return false;
        int a =p.val;
        int b = q.val;
        if(p.val != q.val) return false;
        return true;
    }
}
看完了?留个评分呗?
[0人评了分,平均: 0/5]

本站原创文章皆遵循“署名-非商业性使用-相同方式共享 3.0 (CC BY-NC-SA 3.0)”。转载请保留以下标注:

原文来源:《100. Same Tree》

发表评论

邮箱地址不会被公开。

返回顶部