[B] [C] [D]

Given the root nodes p and q of two binary trees, write a function to check whether the two trees are the same.

Two trees are considered identical if they are structurally identical and the nodes have the same value.

Example 1:

Input: p = [1,2,3], q = [1,2,3] output: trueCopy the code

Example 2:

Input: p = [1,2], q = [1, NULL,2] Output: falseCopy the code

Example 3:

Input: p = [1,2,1], q = [1,1,2] output: falseCopy the code

Tip:

  • The number of nodes in both trees is in the range[0, 100] 内
  • -104 <= Node.val <= 104

Their thinking

To judge whether two binary trees are completely equal, we can recursively compare whether each subtree is equal. If all subtrees are equal, the two binary trees are proved to be completely equal.

Code implementation

Var isSameTree = function(p, q) {function check(a,b){// If both nodes are null, If (a===null && b===null) return true; / / if a node is empty or two different node value, is not equal to the if (a = = = null | | b = = = null | | (Dr. Al! ==b.val)) return false; Return check(a.lift, B.lift)&&check(A.light, b.light)} return check(p,q)};Copy the code

At this point we are done with Leetcode-100 – the same tree

If you have any questions or suggestions, please leave a comment!