lintcode,等价二叉树
来源:互联网 发布:林心如人设崩塌知乎 编辑:程序博客网 时间:2024/05/20 23:34
检查两棵二叉树是否等价。等价的意思是说,首先两棵二叉树必须拥有相同的结构,并且每个对应位置上的节点上的数都相等。
一刷ac
解题思路:用递归和非递归分别实现。都是细节问题,递归判断两个节点是否全不为空,是否值相等,一集左右子树是否等价。非递归用两个栈存两个数的节点,每次存放一个节点,并判断另一个树能不能做相同的存放。
递归实现
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */public class Solution { /** * @param a, b, the root of binary trees. * @return true if they are identical, or false. */ public boolean isIdentical(TreeNode a, TreeNode b) { if(a == null && b == null) return true; if(a == null || b == null) return false; if(a.val != b.val) return false; return isIdentical(a.left, b.left) && isIdentical(a.right, b.right); }}
非递归实现。
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */public class Solution { /** * @param a, b, the root of binary trees. * @return true if they are identical, or false. */ public boolean isIdentical(TreeNode a, TreeNode b) { if(a == null && b == null) return true; if(a == null || b == null) return false; Stack<TreeNode> stacka = new Stack<TreeNode>(); Stack<TreeNode> stackb = new Stack<TreeNode>(); stacka.push(a); stackb.push(b); while(!stacka.empty() && !stackb.empty()){ TreeNode nodea = stacka.pop(); TreeNode nodeb = stackb.pop(); if(nodea.val != nodeb.val) return false; if(nodea.left != null){ if(nodeb.left == null) return false; if(nodea.left.val == nodeb.left.val){ stacka.push(nodea.left); stackb.push(nodeb.left); }else return false; } if(nodea.right != null){ if(nodeb.right == null) return false; if(nodea.right.val == nodeb.right.val){ stacka.push(nodea.right); stackb.push(nodeb.right); }else return false; } } return stacka.empty() && stackb.empty(); }}
0 0
- LintCode:等价二叉树
- lintcode ----等价二叉树
- 等价二叉树-lintcode
- 等价二叉树,lintcode
- lintcode-->等价二叉树
- lintcode,等价二叉树
- LintCode-等价二叉树
- LIntCode 等价二叉树
- 等价二叉树-LintCode
- Lintcode 等价二叉树
- LintCode 等价二叉树
- 等价二叉树-LintCode
- LintCode - 469.等价二叉树
- lintcode 469 等价二叉树
- LintCode 469-等价二叉树
- [LintCode]469.等价二叉树
- [Lintcode] #469 等价二叉树
- lintCode(469)——等价二叉树
- 洞悉特性、属性和样式
- React-Native-Android-Studio整合开发+环境配置+官方实例
- WebService请求服务器,4.0系统出现java java.lang.NoClassDefFoundError错误
- RatingBar设置不可点击解决办法
- SpringMVC绑定ajax传递json数据到pojo对象错误(400 Bad Request)
- lintcode,等价二叉树
- C/C++中extern关键字详解
- 一维、二维正态分布概率密度曲线的绘制
- Gpio模拟i2c总线对24c02进行读写
- IOS开发学习过程问题点记录
- Java_正则表达式
- Linux并发服务器编程之IO多路复用
- 算法总结
- eclipse 关闭控制台 自动弹出