• LeetCode 100. 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.


     题目标题:Tree
      这道题目给了我们两个二叉树,让我们判断这两个二叉树是否一摸一样。利用preOrder 来遍历tree, 对于每一次判断,有三种可能性:
      1- 如果两个点都等于null -> 意思就是到达了最低端,并且它们是相等的,return true;
      2- 如果一个点等于null, 另外一个点不等于null, 那么它们是不相等的,return false;
      3- 如果两个点都不是null, 并且它们的值不相等,return false;
     
      剩下的情况就是它们两个点的值是相等的,把它们left 和 right children继续代入isSameTree function, 利用 && 来控制,一个点的left 和 right 返回的都是true,这个点返回的才是true。
     
     

    Java Solution:

    Runtime beats 23.17% 

    完成日期:07/01/2017

    关键词:Tree

    关键点:利用preOrder 来遍历tree;利用&&来控制左右两个children返回的都是true,才等于true。

     1 /**
     2  * Definition for a binary tree node.
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 public class Solution 
    11 {
    12     public boolean isSameTree(TreeNode p, TreeNode q) 
    13     {
    14         if(p == null && q == null)
    15             return true;
    16         if(p == null || q == null)
    17             return false;
    18         
    19         if(p.val != q.val)
    20             return false;
    21         
    22         
    23         return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    24         
    25     }
    26 }

    参考资料:N/A

    LeetCode 算法题目列表 - LeetCode Algorithms Questions List

  • 相关阅读:
    选择排序
    【洛谷8341】[AHOI2022] 回忆(贪心)
    swagger在高版本springboot中的使用
    springboot中关于连接池的几种方式
    MySQL 的 delete、truncate、drop 有什么区别?
    Docker容器命令
    IDEA 神级插件!效率提升 20 倍!
    Bean Searcher——多条件查询神器
    8 种最坑SQL语法,工作中踩过吗?
    消息中间件:rocketmq单机安装部署
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/7103609.html
Copyright © 2020-2023  润新知