zoukankan      html  css  js  c++  java
  • [LeetCode]100、Same Tree

    题目描述:

    Given two binary trees, write a function to check if they are the same or not.

    Two binary trees are considered the same if they are structurally identical and the nodes have the same value.

    Example 1:

    Input:     1         1
              /        / 
             2   3     2   3
    
            [1,2,3],   [1,2,3]
    
    Output: true
    

    Example 2:

    Input:     1         1
              /           
             2             2
    
            [1,2],     [1,null,2]
    
    Output: false
    

    Example 3:

    Input:     1         1
              /        / 
             2   1     1   2
    
            [1,2,1],   [1,1,2]
    
    Output: 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 public class Solution100 {
    11     public boolean isSameTree(TreeNode p, TreeNode q) {
    12         if(p==null && q == null){return true;}
    13         if(p==null || q == null){return false;}
    14         if(p.val == q.val){return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);}
    15         else return false;
    16     }
    17     public static void main(String[] args) {
    18         // TODO Auto-generated method stub
    19         Solution100 solution100 = new Solution100();
    20         TreeNode p = new TreeNode(0);
    21         p.left = new TreeNode(2);
    22         p.right = new TreeNode(3);
    23         TreeNode q = new TreeNode(1);
    24         q.left = new TreeNode(2);
    25         q.right = new TreeNode(3);
    26         if(solution100.isSameTree(p, q)){System.out.println("yes");}
    27         else {
    28             System.out.println("no");
    29         }
    30     }
    31 
    32 }
  • 相关阅读:
    今日进度
    今日进度
    今日进度
    今日进度
    pandas连接MySQL和impala
    sql语句获取今天、昨天、近7天、本周、上周、本月、上月、半年数据
    Python报错 ValueError: arrays must all be same length
    Python 连接 impala
    Test
    Selective Search for Object Recognition
  • 原文地址:https://www.cnblogs.com/zlz099/p/8145004.html
Copyright © 2011-2022 走看看