题目描述:https://leetcode-cn.com/problems/same-tree/
这个题目只要按照相同的顺序遍历一遍节点,判断节点是否相等即可,注意下对空节点的处理就好
public boolean isSameTree(TreeNode p, TreeNode q) {
Stack<TreeNode> stack = new Stack<>();
stack.add(p);
stack.add(q);
while (!stack.isEmpty()) {
TreeNode pNode = stack.pop();
TreeNode qNode = stack.pop();
if ((Objects.isNull(pNode) && Objects.nonNull(qNode))
||(Objects.isNull(qNode) && Objects.nonNull(pNode))){
return false;
}else if (Objects.nonNull(pNode)&&Objects.nonNull(qNode)){
if (!Objects.equals(pNode.val, qNode.val)) {
return false;
}
stack.add(pNode.left);
stack.add(qNode.left);
stack.add(pNode.right);
stack.add(qNode.right);
}
}
return true;
}