LeetCode 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 :
    这里写图片描述
  • 地址

问题分析

  • 递归(类似前序遍历)
  • 类似前序遍历非递归形式(可以用两个栈,也可以用一个栈,一次弹出来两个
  • 层序遍历(可以用两个队列,也可以用一个队列,一次出队两个进行比较

代码实现

  • 递归
public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null && q == null) {
            return true;
        }
        if (p == null || q == null) {
            return false;
        }
        return (p.val == q.val) && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }
  • 层序遍历
//有点类似于层序遍历的序列化,空结点也要入队,但是空结点的孩子不再入队
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null && q == null) {
            return true;
        }
        if (p == null || q == null) {
            return false;
        }
        LinkedList<TreeNode> pQueue = new LinkedList<>();
        LinkedList<TreeNode> qQueue = new LinkedList<>();
        pQueue.add(p);
        qQueue.add(q);
        while (! pQueue.isEmpty() && ! qQueue.isEmpty()) {
            TreeNode pNode = pQueue.remove();
            TreeNode qNode = qQueue.remove();
            if (pNode == null && qNode == null) {//空结点的孩子不再入队
                continue;
            }
            if (pNode == null || qNode == null || pNode.val != qNode.val) {
                return false;
            }
            //两节点都非空
            pQueue.add(pNode.left);
            pQueue.add(pNode.right);
            qQueue.add(qNode.left);
            qQueue.add(qNode.right);
        }
        return pQueue.size() == qQueue.size();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值