首页 > 其他 > 详细

【LeetCode】Same Tree

时间:2019-09-18 18:42:03      阅读:63      评论:0      收藏:0      [点我收藏+]

【Description】

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

【AC code】

Reference: https://leetcode.com/articles/same-tree/

一、递归  时间复杂度:O(n)

技术分享图片
1 class Solution {
2     public boolean isSameTree(TreeNode p, TreeNode q) {
3         if (p == null && q == null) return true;
4         if ((p != null && q == null) || (p == null && q != null) || p.val != q.val) return false;
5         return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
6     }
7 }
View Code

 二、迭代  时间复杂度:O(n)

技术分享图片
 1 class Solution {
 2     public boolean isSameTree(TreeNode p, TreeNode q) {
 3             Queue<TreeNode> queue = new LinkedList<>();
 4             queue.offer(p);
 5             queue.offer(q);
 6             while (!queue.isEmpty()) {
 7                 TreeNode first = queue.poll();
 8                 TreeNode second = queue.poll();
 9                 if (first == null && second == null) continue;
10                 if ((first == null || second == null) || first.val != second.val) return false;
11                 queue.offer(first.left);
12                 queue.offer(second.left);
13                 queue.offer(first.right);
14                 queue.offer(second.right);
15             }
16             return true;
17     }
18 }
View Code

 

【拓展知识】

Reference: https://blog.csdn.net/u012050154/article/details/60572567

在第二种方法中队列的入队和出队分别采用了offer()和poll(),而不是add()和remove(),这是为了便于程序有效判断。

【LeetCode】Same Tree

原文:https://www.cnblogs.com/moongazer/p/11536142.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!