zoukankan      html  css  js  c++  java
  • leetcode -- 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.

     1 /**
     2  * Definition for binary tree
     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     public boolean isSameTree(TreeNode p, TreeNode q) {
    12         // Start typing your Java solution below
    13         // DO NOT write main() function
    14         if((p == null) && (q == null)){
    15             return true;
    16         } else if((p != null) && (q != null)){
    17             return cmp(p, q);
    18         } else {
    19             return false;
    20         }
    21         
    22     }
    23     
    24     public boolean cmp(TreeNode p, TreeNode q){
    25         if(p.val != q.val){
    26             return false;
    27         }
    28         
    29         TreeNode pl = p.left, pr = p.right;
    30         TreeNode ql = q.left, qr = q.right;
    31         
    32         if(((pl == null) && (ql != null)) || ((pl != null) && (ql == null))){
    33             return false;
    34         }
    35         
    36         if(((pr == null) && (qr != null)) || ((pr != null) && (qr == null))){
    37             return false;
    38         }
    39         boolean lFlag = true;
    40         boolean rFlag = true;
    41         if((pl != null) && (ql != null)){
    42             lFlag = cmp(pl, ql);
    43         }
    44         if((pr != null) && (qr != null)){
    45             rFlag = cmp(pr, qr);
    46         }
    47         return lFlag && rFlag;
    48     }
    49 }
  • 相关阅读:
    imp.load_source的用法
    第12周翻译
    第十周学习笔记
    翻译:高级t
    t-sql
    9周学习笔记
    第8周学习笔记
    t-sql的楼梯:超越基本级别6:使用案例表达式和IIF函数
    数据库设计层次3:构建表
    第七周学习笔记
  • 原文地址:https://www.cnblogs.com/feiling/p/3250920.html
Copyright © 2011-2022 走看看