Title Description
Given two binary tree, write a function to check whether they are identical.
If the two are identical in structure tree, and the nodes have the same value, they are considered identical.
Ideas analysis
- A thought: see use case, think of the most troublesome practices. Two trees with the first array traverse the level storage array for comparison.
- Thinking two: the recursion. First determine p, q is empty, and then determine their values are equal. If the above is determined by recursively sub-node to do the same operation.
Code
/**
* 递归解法
* @param p
* @param q
* @return
*/
public static boolean isSameTree1(TreeNode p, TreeNode q) {
if (p == null && q == null) {
return true;
}
if (p == null || q == null) {
return false;
}
if (p.val != q.val) {
return false;
}
return isSameTree1(p.left, q.left) && isSameTree1(p.right, q.right);
}
/**
* 层次遍历解法
* @param p
* @param q
* @return
*/
public static boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null && q == null) {
return true;
}
if (p == null || q == null) {
return false;
}
ArrayList<Integer> arrayList1 = levelOrder(p);
ArrayList<Integer> arrayList2 = levelOrder(q);
if (arrayList1.size() != arrayList2.size()) {
return false;
}
int i = 0;
while (i < arrayList1.size() && i < arrayList2.size()) {
if (!arrayList1.get(i).equals(arrayList2.get(i))) {
return false;
}
i++;
}
return true;
}
public static ArrayList<Integer> levelOrder(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
ArrayList<Integer> arrayList = new ArrayList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
while (size-- > 0) {
TreeNode tmp = queue.poll();
if (tmp == null) {
arrayList.add(0);
continue;
}
arrayList.add(tmp.val);
queue.offer(tmp.left);
queue.offer(tmp.right);
}
}
return arrayList;
}