zoukankan      html  css  js  c++  java
  • leetcode------Same Tree

    标题:

    Same Tree
    通过率: 42%
    难度 简单

    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.

    这道题是自己的失误造成了第一次提交的失败,原因是题目没有看清楚。然后是对于二叉树的相同没有弄明白,如果想用对比节点相同的话还是要重写equals方法,显然本题是不能用的,那么就是节点的值比较,左右子树递归,具体步骤如下:

    1、p、q两树均为空则返回true

    2、p、q两树有且仅有一个树为空则返回false

    3、p、q两树的节点值相同,则继续进行递归。

    4、其他情况全部返回false

    对于继续递归,则要用 (p.right,q.right)&&(p.left,q.left)两树左右都相同才能是完全的相同。这个题目直接看代码则能看出算法的步骤

     1 public class Solution {
     2     public boolean isSameTree(TreeNode p, TreeNode q) {
     3         return vistree(p,q);
     4     }
     5     public boolean vistree(TreeNode p,TreeNode q){
     6         if(p==null&&q==null) return true;
     7         if(p==null&&q!=null) return false;
     8         if(p!=null&&q==null) return false;
     9         if(p.val==q.val){
    10             return vistree(p.right,q.right)&&vistree(p.left,q.left);
    11         }
    12         else return false;
    13     }
    14 }
  • 相关阅读:
    (转)C#中String跟string的“区别”
    C#中的this关键字
    (转)VS2015基础 指定一个或多个项目执行
    C# 中如何输出双引号(转义字符的使用)
    (转) C#中使用throw和throw ex抛出异常的区别
    springboot
    Zookeeper
    Maven
    springboot
    springboot
  • 原文地址:https://www.cnblogs.com/pkuYang/p/4158414.html
Copyright © 2011-2022 走看看