LeetCode No.100 Same Tree | #Tree

Q:

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.

A:

/**
 * 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); //迭代! 
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • “什么垃圾,也来这里发表文章” 可能是吧,文笔差,看的书也不多,也不是某某中文毕业的,确实没什么资格给大家分享 但...
    7e1529120fd8阅读 511评论 0 0
  • 碎戏台词说:我家后院养了一条狗一只羊 狗觉得羊啃不了骨头就不幸福 羊觉得狗吃不了青草就不幸福 我说:你是大都市橱窗...
    马桶左便器阅读 109评论 0 0
  • 加入圈子,写写写! 没加入小灶群时,想都没想过自己有“写作”的能力。 因为从大脑中按思路来码出字,对从不看书的我来...
    灵魂兽者阅读 183评论 1 4
  • 我曾无数次路过你在每一个消亡了星星的黑夜里你抿嘴的样子你时而高亢时而低沉的表情你模糊而渐远的身影都那么的清晰 我不...
    劳心者阅读 352评论 19 0