leetcode100,101(C#)

今天数据结构课小测考了两道关于树的题目,总结下来,顺便学习递归:

  1. leetcode 100

\100. Same Tree

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

在树的的很多应用中,都运用到了递归的思想,这道题同样也是,但同时也可以用迭代的思路去做。

递归的关键就是找到 递归终止条件、将问题分解为解决逻辑相同的子问题来解决。

明白思路,这道题很快就能做出来了。代码如下:

public class Solution {
    public bool IsSameTree(TreeNode p, TreeNode q) {
        if (p == null && q == null)
            return true;
        //if ((p != null && q == null) || (p == null && q != null)) 这句代码可以优化一下,使之更简洁
        if (p == null || q == null)
            return false;
        if (p.val != q.val)
            return false;
        if (IsSameTree(p.left, q.left))
            return (IsSameTree(p.right, q.right));
        return false;
    }
}

可以看到,使用递归可以让代码变得很简洁,但递归同样也存在自己的问题,但大量调用时往往会消耗大量的内存。

  1. leetcode 101

\101. Symmetric Tree

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

    1
   / \
  2   2
 / \ / \
3  4 4  3

But the following [1,2,2,null,3,null,3] is not:

    1
   / \
  2   2
   \   \
   3    3

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

    1
   / \
  2   2
 / \ / \
3  4 4  3

But the following [1,2,2,null,3,null,3] is not:

    1
   / \
  2   2
   \   \
   3    3

这道题的思路与上一道题很相像,只不过第一道题中 是两棵树比较,这道题是一棵树比较,而且第一道题要求的是左右结点相等,而第二道题要求的是左右子树成镜像关系。

在做的时候注意一些细节上的差别,用上一题的思路,很快也能做出来。代码如下:

public class Solution {
    public bool IsSymmetric(TreeNode root) {
        if (root == null)
            return true;
        return IsEqual(root.left, root.right);
    }
    
    private bool IsEqual(TreeNode p, TreeNode q)
    {
        if (p == null && q == null)
            return true;
        if (p == null || q == null)
        //if ((p != null && q == null) || (p == null && q != null))
            return false;
        if (p.val != q.val)
            return false;
        if (IsEqual(p.left, q.right))
            return IsEqual(p.right, q.left);
        return false;
        // 后三行代码同样可以优化使之更简洁
        // return IsEqual(p.left, q.right) && IsEqual(p.right, q.left);
    }
}

以上都是用递归来做,在学习完递归之后,可以试试迭代的思路

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值