Same Tree (E)
题目
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
题意
判断两个二叉树是否完全一样。
思路
递归比较每一个结点是否相同。
代码实现
Java
/**
* 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;
} else if (p == null || q == null || p.val != q.val) {
return false;
} else {
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
}
}
JavaScript
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} p
* @param {TreeNode} q
* @return {boolean}
*/
var isSameTree = function (p, q) {
if (!p && !q) {
return true
} else if (!p || !q || p.val !== q.val) {
return false
}
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right)
}