題目描述:https://leetcode-cn.com/problems/same-tree/
這個(gè)題目只要按照相同的順序遍歷一遍節(jié)點(diǎn),判斷節(jié)點(diǎn)是否相等即可,注意下對(duì)空節(jié)點(diǎn)的處理就好
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;
}