博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Leetcode]100. Same Tree -David_Lin
阅读量:6866 次
发布时间:2019-06-26

本文共 969 字,大约阅读时间需要 3 分钟。

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.

思路:同时递归两棵树,如果节点值不相等或者一棵树已经递归到头了而另一棵还没有,返回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 class Solution {11     public boolean isSameTree(TreeNode p, TreeNode q) {12         if (p==null&&q==null)13             return true;                 //一开始如果传进两颗空树,返回true14         if ((p==null&&q!=null)||(p!=null&&q==null))15             return false;                //递归过程中,一棵树递归到头了,而另一颗没有16         if (p.val!=q.val)17             return false;18         return isSameTree(p.left,q.left)&&isSameTree(p.right,q.right); 19                                               // 同时递归20     }21 }

 

转载于:https://www.cnblogs.com/David-Lin/p/7692589.html

你可能感兴趣的文章
vuex相关(actions和mutation的异曲同工)
查看>>
Linux常用命令总结
查看>>
即时通讯软件的发展演变
查看>>
java基础总结
查看>>
算法复杂度
查看>>
Jsonlib 属性过滤器
查看>>
List 去重
查看>>
Android性能优化之内存优化练习
查看>>
LeetCode 465: Optimal Account Balance
查看>>
LeetCode – Refresh – Trapping Rain Water
查看>>
通达OA数据库优化方案之_历史数据清理
查看>>
持续集成之③:将代码自动部署至测试环境
查看>>
第三十五课:Ajax详解
查看>>
Python基础之各种推导式玩法
查看>>
poj 3167(KMP+树状数组)
查看>>
C++ 循环队列基本算法实现
查看>>
maven中,dependency 中的 classifier属性
查看>>
51Nod-1011 最大公约数GCD【欧几里得算法】
查看>>
#从零开始学Swift2.0# No.2 运算符和表达式
查看>>
Ubuntu下安装NetBeans步骤和相关问题的解决方法
查看>>