加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

[leetcode]100.Same Tree

发布时间:2020-12-14 04:21:15 所属栏目:大数据 来源:网络整理
导读:题目 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. 解法一 思路 先序遍历的递归 代码 /** * Definit

题目

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.

解法一

思路

先序遍历的递归

代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isSameTree(TreeNode p,TreeNode q) {
        if(p == null && q == null) return true;
        if(p == null || q == null) return false;
        if(p.val != q.val)
            return false;
        return isSameTree(p.left,q.left)&&isSameTree(p.right,q.right);
    }
}

解法二

思路

用栈或者队列来实现层次遍历,一个栈(队列) 或者 两个栈(队列)都可以。如果用一个栈(队列),那就是两棵树同一个位置的节点同时入栈,出栈的时候同时出栈,然后进行对比。以下用一个队列实现。

代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isSameTree(TreeNode p,TreeNode q) {
        Deque<TreeNode> queue = new LinkedList<>();
        queue.addLast(p);
        queue.addLast(q);
        while(!queue.isEmpty()){
            p = queue.removeFirst();
            q = queue.removeFirst();
            
            if(p == null && q == null)
                continue;
            else if(p == null || q == null || q.val!=p.val)
                return false;
            else {
                queue.addLast(p.left);
                queue.addLast(q.left);
                queue.addLast(p.right);
                queue.addLast(q.right);
            }
        }
        return true;
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读