今天数据结构课小测考了两道关于树的题目,总结下来,顺便学习递归:
- 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;
}
}
可以看到,使用递归可以让代码变得很简洁,但递归同样也存在自己的问题,但大量调用时往往会消耗大量的内存。
- 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);
}
}
以上都是用递归来做,在学习完递归之后,可以试试迭代的思路