[Leetcode]100. Same Tree -David_Lin
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; //一开始如果传进两颗空树,返回true 14 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
[Leetcode]100. Same Tree -David_Lin相关推荐
- LeetCode 100. Same Tree
LeetCode 100. Same Tree Solution1: 这种弱智题提交这么多次... /*** Definition for a binary tree node.* struct Tr ...
- [LeetCode]: 100: Same Tree
题目: Given two binary trees, write a function to check if they are equal or not. Two binary trees are ...
- [leetcode]100.Same Tree
题目 Given two binary trees, write a function to check if they are the same or not. Two binary trees a ...
- leetcode 100.Same Tree
这道题目我最初想的太多了,导致做了好久,之后从网上一看,一下醒悟过来,不难. 题目: Given two binary trees, write a function to check if they ...
- LeetCode 589. N-ary Tree Preorder Traversal-多子节点树前序遍历--递归,迭代--反向压栈--C++解法
LeetCode 589. N-ary Tree Preorder Traversal-多子节点树前序遍历–递归,迭代–反向压栈–C++解法 LeetCode题解专栏:LeetCode题解 LeetC ...
- LeetCode: 107. Binary Tree Level Order Traversal II
题目 Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from l ...
- LeetCode: 103. Binary Tree Zigzag Level Order Traversal
题目 Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left ...
- LeetCode: Flatten Binary Tree to Linked List
LeetCode: Flatten Binary Tree to Linked List LeetCode: Flatten Binary Tree to Linked List Given a bi ...
- 【重点】LeetCode 124. Binary Tree Maximum Path Sum
LeetCode 124. Binary Tree Maximum Path Sum 参考链接:http://zxi.mytechroad.com/blog/tree/leetcode-124-bin ...
最新文章
- nginx学习之静态内容篇(五)
- Java文件非法字符
- 021_Form表单
- 【Linux入门连载三】Linux常用的基本命令
- Dw序号列表如何通过html语言加,html标签属性大全
- druid 多数据源_Spring Boot + Mybatis 中 配置Druid多数据源并实现自由切换
- Quartz框架中的Trigger
- cocos2d-x游戏实例(23)-简易动作游戏(1)
- 金三银四跳槽面试季,我整理前端知识做了个网站
- java接口import_深入理解Java架构师在组件注册@Import导入容器(ImportSelector接口)的神操作!...
- html如何查看文档,查看文档
- w7提示无法关闭计算机,win7关不了机怎么回事?老司机教你怎么解决电脑关不了机...
- ubuntu内核损坏或误删除时的系统修复
- 过年不回家,压岁钱、份子钱省下来了吗?
- sharepoint2013列表实现项目级权限控制
- 2017,三大运营商的天猫芳华
- 手机登入注册为什么出现这个错误?
- win10开机字体变大bug
- C语言/c++:实验报错[Error] ld returned 1 exit status的解决方案
- UVA11584---区间DP