问题:
难度:easy
说明:
给出两个二叉树,要求判断两棵树是否相同,就是判断节点值是否一致。
问题链接:https://leetcode.com/problems/same-tree/
输入案例:
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
我的代码
水题,用 栈 进行 DFS 或者 BFS 都行,又或者 用递归 DFS BFS。
使用递归 DFS,BFS改为双栈(滚动数组):
class Solution {
private boolean sameFlag = true;
public boolean isSameTree(TreeNode p, TreeNode q) {
if(!sameFlag) return sameFlag;
boolean p1 = p != null;
boolean q1 = q != null;
// 只有一个 null,把标记打为 false
if(p1 ^ q1) sameFlag = false;
// 两者非空
else if(p1 ) {
// 值不一样就将标记打为 false
if(p.val != q.val)
{
sameFlag = false;
}
else
{
isSameTree(p.left,q.left);
isSameTree(p.right,q.right);
}
}
return sameFlag;
}
}
使用 栈 DFS,BFS 也是双栈(滚动数组)就行:
class Solution {
private static int top = 0;
private static TreeNode[] stack = new TreeNode[(int)Math.pow(2,10)];
public boolean isSameTree(TreeNode p, TreeNode q) {
top = 0;
stack[top ++] = p;
stack[top ++] = q;
while(top != 0) {
TreeNode p0 = stack[-- top];
TreeNode q0 = stack[-- top];
boolean p0e = p0 == null;
boolean q0e = q0 == null;
if(!p0e && !q0e) {
if(p0.val != q0.val)
return false;
stack[top ++] = p0.left;
stack[top ++] = q0.left;
stack[top ++] = p0.right;
stack[top ++] = q0.right;
}
else if(q0e ^ p0e)
return false;
}
return true;
}
}