您的位置:首页 > 其它

个人记录-LeetCode 100. Same Tree

2017-04-20 14:51 363 查看
问题:

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.

这个问题比较简单,就是判断两颗树是否完全相等。

代码示例:

我们之间先序遍历比较一下即可。

代码类似于:

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null && q == null) {
return true;
}

//先序遍历,先当前节点
//然后左子树,再右子树
if (p != null && q != null && p.val == q.val) {
return isSameTree(p.left, q.left)
&& isSameTree(p.right, q.right);
}

return false;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: