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

    相同的树。题意是给两个树,判断他们是否相同。有两种思路,bfs和dfs。bfs是按层遍历tree,将每层的node塞进queue然后弹出比较,需要注意塞进queue的顺序。此处我只实现了dfs的做法。

    时间O(n)

    空间O(n)

    JavaScript实现

     1 /**
     2  * @param {TreeNode} p
     3  * @param {TreeNode} q
     4  * @return {boolean}
     5  */
     6 const isSameTree = function(p, q) {
     7     // corner case
     8     if (p == null && q == null) return true;
     9     if (p == null || q == null) return false;
    10 
    11     // normal case
    12     if (p.val == q.val) {
    13         return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    14     }
    15     return false;
    16 };

    Java实现

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

    相关题目

    100. Same Tree

    572. Subtree of Another Tree

    LeetCode 题目总结

  • 相关阅读:
    模型分离(选做)
    密码保护
    实现搜索功能
    完成个人中心—导航标签
    个人中心标签页导航
    评论列表显示及排序,个人中心显示
    完成评论功能
    从首页问答标题到问答详情页
    IDEA常用快捷键
    就业培训学习记录-day010
  • 原文地址:https://www.cnblogs.com/cnoodle/p/12159352.html
Copyright © 2011-2022 走看看