【LeetCode】Same Tree

【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/

A recursive  time complexity: 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

 Second, the iteration  time complexity: 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

 

[Expand] knowledge

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

In the second method the queue enqueue and dequeue were used the offer () and poll (), rather than add () and remove (), which is determined in order to facilitate effective application.

Guess you like

Origin www.cnblogs.com/moongazer/p/11536142.html