白话数据结构之二叉树(Same Tree)java,C实现

   小哥我今日突然诗性大发想写点什么,可是又找不到头绪于是乎直接打开google,登陆leetcode 找到database 目录栏的tree栏目。闲话我们从倒数的第一个题目开始先带着大家从easy 部分开始。当然先从java部分开始。
对于树的基本概念还比较模糊的同学请自行查阅相关文档文章,这里我也推荐一篇博客:

http://blog.csdn.net/pony_maggie/article/details/38390513

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遍历的方法也完成了,这是小哥我发的第一篇技术博客,欢迎大家拍砖。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值