您的位置:首页 > 编程语言 > Java开发

【leetcode】【100】Same Tree

2016-03-04 10:28 525 查看

一、问题描述

Given two binary trees, write a function to check if they are equal or not.

Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

二、问题分析

树的遍历问题。一般情况下只是遍历一棵树,此题无非同时遍历两个树罢了。采用先序遍历,当然也可以采用其它的。

三、Java AC代码

public boolean isSameTree(TreeNode p, TreeNode q) {
return preOrderTravel(p, q);
}
public boolean preOrderTravel(TreeNode p, TreeNode q) {
if (p==null && q==null) {
return true;
}
if (p==null && q!=null) {
return false;
}
if (p!=null && q == null) {
return false;
}
if (p.val == q.val) {
return preOrderTravel(p.left, q.left) && preOrderTravel(p.right, q.right);
}else {
return false;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java leetcode tree