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

    Subscribe to see which companies asked this question

    题目解析:

    判断两个树是否为相同的二叉树。一般二叉树类型的题都有两种解法,recursive的和non-iterative的。

    非迭代方法:

    如果是非迭代的方式,基本上就是用一个LinkedList或Queue或者Stack的数据结构作为中间件来存储树中的点,然后使用一个while循环来判断这个数据结构是否为空,如果为空就退出循环。

    对于这道题来说,需要有两个Stack分别存储的是两个树的不同节点,然后判断节点的不同情况:

    1. p节点为空,q节点不为空      return false

    2. p节点不为空,q节点为空      return false

    3. p、q节点都不为空但是值不相等   return false

    4. p、q节点都不为空,值相等     return true

     1 public boolean isSameTree(TreeNode p, TreeNode q) {
     2         LinkedList<TreeNode> l1 = new LinkedList<TreeNode>(),
     3                              l2 = new LinkedList<TreeNode>();
     4         l1.add(p);
     5         l2.add(q);
     6         
     7         while(!l1.isEmpty() && !l2.isEmpty()){
     8             TreeNode c1 = l1.poll();
     9             TreeNode c2 = l2.poll();
    10             
    11             if(c1 == null){
    12                 if(c2 == null)  continue;
    13                 else    return false;
    14             }
    15             if(c2 == null || c1.val != c2.val)  return false;
    16             l1.add(c1.left);
    17             l1.add(c1.right);
    18             
    19             l2.add(c2.left);
    20             l2.add(c2.right);
    21         }
    22         return true;
    23         
    24     }

    迭代方法:

    1 public boolean isSameTree(TreeNode p, TreeNode q) {
    2         if(p == null && q == null)  return true;
    3         if(p == null || q == null)  return false;
    4         
    5         return (p.val == q.val) && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    6         
    7     }
  • 相关阅读:
    C#中Post和Get提交
    C#实现动态页面静态化
    瀑布流的实现
    jQuery常用方法验证
    eclipse配置PHP开发环境
    数据结构学习
    机器学习实战
    Leetcode_StringToInteger
    网络学习
    leetcode_前期心得
  • 原文地址:https://www.cnblogs.com/sherry900105/p/4929142.html
Copyright © 2011-2022 走看看