小哥我今日突然诗性大发想写点什么,可是又找不到头绪于是乎直接打开google,登陆leetcode 找到database 目录栏的tree栏目。闲话我们从倒数的第一个题目开始先带着大家从easy 部分开始。当然先从java部分开始。
对于树的基本概念还比较模糊的同学请自行查阅相关文档文章,这里我也推荐一篇博客:
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.
Subscribe to see which companies asked this question.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
bool isSameTree(struct TreeNode* p, struct TreeNode* q) {
}
算法分析:二叉树相等,那么必须是从根节点开始的左右子树都相等,要判断相等,必须要遍历树,该用深度遍历还是广度遍历呢?小哥我先带大家用深度遍历法实现,深度遍历肯定要结合递归方法。
这里写代码片
`
``bool isSameTree(struct TreeNode* p, struct TreeNode* q) {
//1. exception protection
//2 when both of tree are empty,LOL we should reture true;
if(p == NULL && q == NULL){
return true;
}else if(p == NULL || q == NULL) {
return false; // why?
}
// 3.开始递归与判断(为啥不用英文了,因为小哥我不知道英文的递归咋写)
return (p->val == q->val) && isSameTree(p->left,q->left)
&& isSameTree(p->right,q->right);
}
`
好了,代码部分实现,以上代码在leetcode上亲测可以通过编译并提交。接下来我们来看看另外一种做法。我们试试用广度优先遍历方法来实现看看,广度优先那么我们需要用到队列或者stack,这里为了方便起见我们就用java来实现。
算法分析:
1、 准备两个队列,分别用来存在左右子树的节点。
2、将根节点放入队列(先进先出)。
3、开始循环的层次遍历
public class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
//1.prepar two queue leftq and rightq
// 2.put root node into queue
// 3. init tmp TreeNode lq and rq to store root.left node and root.right node.
// 4.clear queue lq and rq.
LinkedList<TreeNode> leftq = new LinkedList<TreeNode>();
LinkedList<TreeNode> rightq = new LinkedList<TreeNode>();
leftq.offer(p);
rightq.offer(q);
while (leftq.size() != 0 && rightq.size() != 0) {
TreeNode lq = leftq.poll();
TreeNode rq = rightq.poll();
if (lq == null && rq == null) continue;
if (lq == null || rq == null) return false;
if (lq.val != rq.val) return false;
left.offer(lq.left); leftq.offer(lq.right);
right.offer(rq.left); rightq.offer(rq.right);
}
if (leftq.size() != 0 || rightq.size() != 0) return false; // why?please think about it.
return true;
}
}
好啦,BFS遍历的方法也完成了,这是小哥我发的第一篇技术博客,欢迎大家拍砖。