zoukankan      html  css  js  c++  java
  • [Leetcode]100. Same Tree -David_Lin

    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.

    思路:同时递归两棵树,如果节点值不相等或者一棵树已经递归到头了而另一棵还没有,返回false;

     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 class Solution {
    11     public boolean isSameTree(TreeNode p, TreeNode q) {
    12         if (p==null&&q==null)
    13             return true;                 //一开始如果传进两颗空树,返回true
    14         if ((p==null&&q!=null)||(p!=null&&q==null))
    15             return false;                //递归过程中,一棵树递归到头了,而另一颗没有
    16         if (p.val!=q.val)
    17             return false;
    18         return isSameTree(p.left,q.left)&&isSameTree(p.right,q.right); 
    19                                               // 同时递归
    20     }
    21 }
  • 相关阅读:
    Address already in use: JVM_Bind:80 异常的解决办法
    Spring(转载二)
    Spring(转载一)
    mybatis(二)
    mybatis(一)
    存储过程(二)
    存储过程(一)
    web过滤器
    请求转发和请求重定向
    JavaWeb(二)
  • 原文地址:https://www.cnblogs.com/David-Lin/p/7692589.html
Copyright © 2011-2022 走看看