leetcode100 相同的树

题目如下

给定两个二叉树,编写一个函数来检验它们是否相同。

如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。

示例 1:

输入:       1         1
          / \       / \
         2   3     2   3

        [1,2,3],   [1,2,3]

输出: true
示例 2:

输入:      1          1
          /           \
         2             2

        [1,2],     [1,null,2]

输出: false

1.递归方法求解

每次使用递归方法输入两个对应位置节点作为参数,判断是否相同,相同则返回他们的左右 和 右左节点作为参数的递归函数。Java代码如下

/**
 * 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) {
        return check(p, q);
    }
    public boolean check(TreeNode p, TreeNode q){
        if (p == null && q==null) return true;
        if(p==null || q==null) return false;
        if (p.val != q.val) return false;
        return check( p.left,  q.left) && check(p.right, q.right);
    }

}

2. 非递归方法求解

我是用一个队列来进行求解,每次入队偶数个,出队偶数个。由于对Java中的一些自带的数据结构类不是很了解,我还是用了python中的列表来模拟队列。代码如下

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def isSameTree(self, p, q):
        """
        :type p: TreeNode
        :type q: TreeNode
        :rtype: bool
        """
        nodequeue= []
        nodequeue.append(p)
        nodequeue.append(q)
        while (nodequeue):
            next1 = nodequeue.pop(0)
            next2 = nodequeue.pop(0)            
            if not next1  and not next2:
                continue
            if not next1 or not next2:
                return False
            if next1.val != next2.val:
                return False
            nodequeue.append(next1.left)
            nodequeue.append(next2.left)            
            nodequeue.append(next1.right)            
            nodequeue.append(next2.right)
        return True
posted @ 2019-05-12 11:45  ayang818  阅读(188)  评论(0编辑  收藏  举报