100. Same Tree

100 [Same Tree]
(https://leetcode.com/problems/same-tree/submissions/)

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.

/**


Total Accepted: **130153** Total Submissions: **299759** Difficulty: **Easy**



Hide Company Tags
 [Bloomberg](https://leetcode.com/company/bloomberg/)
Hide Tags
 [Tree](https://leetcode.com/tag/tree/) [Depth-first Search](https://leetcode.com/tag/depth-first-search/)

 * 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 isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
         }
        
        return false;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,357评论 0 33
  • Difficulty : easyGiven two binary trees, write a function...
    greatseniorsde阅读 1,157评论 0 0
  • MRC下的内存管理 引用计数的思考 Objective-C中的内存管理,也就是引用计数。有关内存管理的方法是包含在...
    WellsCai阅读 3,395评论 0 2
  • 读一本书,人们往往想收获点什么,最好是能get到作者的某个重要的点;去吃一顿大餐,除了填饱肚子,大家更期待美食能够...
    鱼鱼爱吃饭阅读 1,733评论 2 2

友情链接更多精彩内容