タイトル説明
2つのバイナリツリーを考えると、それらが同一であるかどうかを確認する関数を記述します。
2は、構造ツリーに同一であり、ノードが同じ値を持っている場合、それらは同一とみなされます。
アイデア解析
- 思考:最も厄介な慣行を考える、ユースケースを参照してください。最初の配列を有する2つのツリーは、比較のためのレベルストレージアレイを横切ります。
- 思考2:再帰。最初のpを決定し、Qが空で、そして次にそれらの値が等しいかを決定。上記は、再帰サブノードによって決定された場合と同じ動作を行います。
コードの実装
/**
* 递归解法
* @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;
}