# 题目

```输入:       1         1
/ \       / \
2   3     2   3

[1,2,3],   [1,2,3]

```示例 2:

/           \
2             2

[1,2],     [1,null,2]

```示例 3::

/ \       / \
2   1     1   2

[1,2,1],   [1,1,2]

# 题解

```/**
* 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) {
return false;
}

if (p.val == q.val) {
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
} else {
return false;
}
}
}```

• 先序遍历
• 中序遍历
• 后序遍历
• 层次遍历

```/**
* 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) {
return false;
}

while(!queue.isEmpty()) {
TreeNode left = queue.poll();
TreeNode right = queue.poll();
if (left == null && right == null) {
// 都是空的,遍历到叶子节点了
continue;
} else if (left == null || right == null) {
// 有一个为null
return false;
} else if (left.val != right.val) {
// 不相等.
return false;
}
// 左子树入队
// 右子树入队
}

return true;
}
}```

```    public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null && q == null) {
return true;
} else if (p == null || q == null) {
return false;
}

Stack<TreeNode> stack = new Stack<>();
stack.push(p);
stack.push(q);
while(!stack.isEmpty()) {
TreeNode left = stack.pop();
TreeNode right = stack.pop();
if (left == null && right == null) {
continue;
} else if (left == null || right == null) {
return false;
} else if (left.val != right.val) {
return false;
}
stack.push(left.left);
stack.push(right.left);
stack.push(left.right);
stack.push(right.right);
}
return true;
}```

337 篇文章94 人订阅

0 条评论