LeetCode Identical Binary Tree 相同二叉树
来源:互联网 发布:linux 查看日志文件 编辑:程序博客网 时间:2024/06/07 20:03
题目描述:
Check if two binary trees are identical. Identical means the two binary trees have the same structure and every identical position has the same value.
样例输入:
1 1 / \ / \ 2 2 and 2 2 / /4 4
1 1 / \ / \ 2 3 and 2 3 / \4 4
样例输出:
truefalse
解法一:
有树的地方就有递归
private boolean isIdenticalRecursion(TreeNode a, TreeNode b) { if (a == null && b == null) { return true; } if ((a == null && b != null) || (a != null && b == null) || (a.val != b.val)) { return false; } return isIdenticalRecursion(a.left, b.left) && isIdenticalRecursion(a.right, b.right);}
解法二:
递归能实现的循环也能实现
private boolean isIdenticalPreOrder(TreeNode a, TreeNode b) { Stack<TreeNode> stack1 = new Stack<>(); Stack<TreeNode> stack2 = new Stack<>(); stack1.push(a); stack2.push(b); while (!stack1.empty() && !stack2.empty()) { TreeNode tmp1 = stack1.pop(); TreeNode tmp2 = stack2.pop(); if (tmp1.val!=tmp2.val){ return false; } if (tmp1.right!=null){ stack1.push(tmp1.right); } if (tmp2.right!=null){ stack2.push(tmp2.right); } if (stack1.size()!=stack2.size()){ return false; } if (tmp1.left!=null){ stack1.push(tmp1.left); } if (tmp2.left!=null){ stack2.push(tmp2.left); } if (stack1.size()!=stack2.size()){ return false; } } return stack1.size() == stack2.size(); }
阅读全文
0 0
- LeetCode Identical Binary Tree 相同二叉树
- 【LeetCode】Identical Binary Tree等价二叉树
- 469.Identical Binary Tree-等价二叉树(容易题)
- Identical Binary Tree
- lintcode:Identical Binary Tree
- [Microsoft] Identical Binary Tree
- 【LeetCode】Balanced Binary Tree,平衡二叉树
- [LeetCode] Balanced Binary Tree 平衡二叉树
- Leetcode Balanced Binary Tree 平衡二叉树
- [LeetCode][二叉树]Invert Binary Tree
- [LeetCode][二叉树]Balanced Binary Tree
- [LeetCode][二叉树]Balanced Binary Tree
- LeetCode随笔之Binary Tree(二叉树)
- LeetCode Invert Binary Tree 翻转二叉树
- leetcode Binary Tree Tilt 二叉树
- 【LeetCode】Invert Binary Tree 翻转二叉树
- 【leetcode】比较两棵二叉树是否相同(Same Tree)
- Leetcode Same Tree 判断两棵二叉树是否相同
- C#读取excel文件,生成json
- abap中VIEW_MAINTENANCE_GIVEN_DATA的用法
- junit 单元测试报错:java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing
- 交叉表格sql语句
- 2017年9月 bug总结
- LeetCode Identical Binary Tree 相同二叉树
- js动态添加带参数的点击事件
- 多设备跨平台,H5天然的便携性
- table表格 td设置固定宽度
- Excel导入数据库回滚
- jfinal根据表创建get set 方法
- 面试知识点总结——网络篇
- Django教程之十一-----模型
- Lucene学习总结之七:Lucene搜索过程解析(7)