zoukankan      html  css  js  c++  java
  • leetcode469:等价二叉树

    1、

      检查两棵二叉树是否等价。等价的意思是说,首先两棵二叉树必须拥有相同的结构,并且每个对应位置上的节点上的数都相等。

     1             1
       /            / 
      2   2   and   2   2
     /             /
    4             4
    

    就是两棵等价的二叉树。

        1             1
       /            / 
      2   3   and   2   3
     /               
    4                 4
    

    就不是等价的。

    2、思路:

      1、首先,判断跟,为空就返回true

      2、其次,当不想等时。一方为空,一方不为空。或者两方的值不相等

      3、再次递归本方法:先左后右

    代码:递归

      

    class TreeNode {
             public int val;
             public TreeNode left, right;
             public TreeNode(int val) {
                 this.val = val;
                 this.left = this.right = null;
             }
         }
    public boolean isIdentical(TreeNode a, TreeNode b) {
             if(a == null && b == null){
                 return true;
             }   
             if(a == null && b != null || a!= null && b == null || a.val != b.val ){
                 return false;
             }
             
             return isIdentical(a.left, b.left) && isIdentical(a.right, b.right);
         }


    工作小总结,有错请指出,谢谢。
  • 相关阅读:
    HDU6060 RXD and dividing
    Knapsack in a Globalized World --多重完全背包
    hdu 6058 Kanade's sum
    矩形面积 HDU
    Bridge Across Islands POJ
    Manors HDU
    Harry Potter and J.K.Rowling HDU
    Polygons HDU
    Jungle Outpost HDU
    CRB and Farm HDU
  • 原文地址:https://www.cnblogs.com/zilanghuo/p/5254870.html
Copyright © 2011-2022 走看看