Problem
https://leetcode.com/problems/same-tree/
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:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
// recursion
// 注意判断p和q是否都为空或其中一个为空
// Complexity:
// Space: O(h) h为树高度,best h = logn 树平衡, worst h = n 树不平衡
// Time: O(n)
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p == null || q == null) {
return p == q;
}
if (p.val == q.val) {
return(isSameTree(p.left, q.left) && isSameTree(p.right, q.right));
}
return false;
}
}
// Iteration 用stack,分别放入两个stack,在pop时比较。
网友评论