给定两棵二叉树,检查它们是否是相同的二叉树
Posted 菜鸟技术栈
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了给定两棵二叉树,检查它们是否是相同的二叉树相关的知识,希望对你有一定的参考价值。
package cn.lspj.ch1.base;
public class CheckSameTree {
public static boolean isSameTree(TreeNode p, TreeNode q) {
if(p == null && q == null) return true;
if(p == null || q == null) return false;
if(p.val == q.val)
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
return false;
}
static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public static void main(String[] args) {
TreeNode pRoot = new TreeNode(1);
TreeNode pLeft = new TreeNode(2);
TreeNode pRight = new TreeNode(3);
pRoot.left = pLeft;
pRoot.right = pRight;
TreeNode qRoot = new TreeNode(1);
TreeNode qLeft = new TreeNode(2);
TreeNode qRight = new TreeNode(3);
qRoot.left = qLeft;
qRoot.right = qRight;
System.out.println(isSameTree(pRoot,qRoot));
}
}
往
期
回
顾
以上是关于给定两棵二叉树,检查它们是否是相同的二叉树的主要内容,如果未能解决你的问题,请参考以下文章