美文网首页
LeetCode实战:相同的树

LeetCode实战:相同的树

作者: 老马的程序人生 | 来源:发表于2019-05-27 17:11 被阅读0次

题目英文

Given two binary trees, write a function to check if they are the same or not.

Two binary trees are considered the same if they are structurally identical and the nodes have the same value.

Example 1:

Input:     1         1
          / \       / \
         2   3     2   3

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

Output: true

Example 2:

Input:     1         1
          /           \
         2             2

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

Output: false

Example 3:

Input:     1         1
          / \       / \
         2   1     1   2

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

Output: false

题目中文

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

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

示例 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

示例 3:

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

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

输出: false

算法实现

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int x) { val = x; }
 * }
 */
 
public class Solution
{
    public bool IsSameTree(TreeNode p, TreeNode q)
    {
        //递归终止条件
        if (p == null && q == null)
            return true;

        if (p != null && q != null && p.val == q.val)
        {
            return IsSameTree(p.left, q.left)
                    && IsSameTree(p.right, q.right);
        }
        return false;
    }
}

实验结果

提交记录

相关图文

相关文章

网友评论

      本文标题:LeetCode实战:相同的树

      本文链接:https://www.haomeiwen.com/subject/niactctx.html