[LeetCode 100] Same Tree (easy)

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

Solution

  1. BSF:用两个Queue分别记录Tree1, Tree2的节点
  2. 每层遍历时,
    • 如果两棵树的当前层的节点数不等时 (Queue.size () 不等),说明节点数不一致,不是Same Tree,直接返回false。
    • 如果两棵树当前的节点都为null,直接跳过判断下一个节点
    • 如果两棵树,当前节点有任一一个为null,或都不为nullvalue不等。也不是Same Tree,直接返回false。

Note: 注意Example2中两棵树是不等的,所以如果左右子树为空时,也需要在BSF中推入Queue,否则无法区别这种情况。

/**
 * 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;
        }
        
        Queue tracker1 = new LinkedList<> ();
        Queue tracker2 = new LinkedList<> ();
        
        tracker1.offer (p);
        tracker2.offer (q);
        
        while (!tracker1.isEmpty () && !tracker2.isEmpty()) {
            int pSize = tracker1.size ();
            int qSize = tracker2.size ();
            
            if (pSize != qSize) {
                return false;
            }
            
            for (int i = 0; i < pSize; i++) {
                TreeNode pNode = tracker1.poll ();
                TreeNode qNode = tracker2.poll ();
                
                if (pNode == null && qNode == null) {
                    continue;
                }
                
                if ((pNode == null || qNode == null) || (pNode != null && qNode != null && pNode.val != qNode.val)) {
                    return false;
                }
                
                tracker1.offer (pNode.left);
                tracker1.offer (pNode.right);
                tracker2.offer (qNode.left);
                tracker2.offer (qNode.right);
            }
        }
        
        return true;
    }
}

你可能感兴趣的:([LeetCode 100] Same Tree (easy))