您的位置:首页 > 其它

100 Same Tree

2015-11-29 20:21 253 查看
题目链接:https://leetcode.com/problems/same-tree/

题目:

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.


解题思路:

这题是 easy ,考点是二叉树的遍历

比较两棵树是否相同,可以用前序,中序或后序遍历。

1. 当两个结点都为空时,说明两棵树在此都终结了。

2. 若一个为空,一个不为空,说明一棵树终结,另一棵还有结点,这两棵树就是不同的二叉树。

3. 当两个结点的值不同时,它们也是不同的二叉树。

很开心,这题和大神写的一样,采用前序遍历,代码十分简洁。

代码实现

/**
* 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)
return false;
if(p.val != q.val)
return false;
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
}


54 / 54 test cases passed.
Status: Accepted
Runtime: 0 ms
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: