Same Tree
2021/7/30 6:06:16
本文主要是介绍Same Tree,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
Code link: https://leetcode.com/problems/same-tree/
- Recursive solution:
class Solution { public boolean isSameTree(TreeNode p, TreeNode q) { if (p == null && q == null) { return true; } else if (p == null || q == null) { return false; } else if (p.val != q.val) { return false; } return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); } }
- Iterative solution
We can also use BFS to do level order traversal, with the help of a queue.
class Solution { public boolean isSameTree(TreeNode p, TreeNode q) { Queue<TreeNode> queue = new LinkedList<>(); queue.add(p); queue.add(q); while (!queue.isEmpty()) { TreeNode lNode = queue.remove(); TreeNode rNode = queue.remove(); if (lNode == null && rNode == null) { continue; } else if (lNode == null || rNode == null) { return false; } else if (lNode.val != rNode.val) { return false; } queue.add(lNode.left); queue.add(rNode.left); queue.add(lNode.right); queue.add(rNode.right); } return true; } }
Similar problem:
- Symmetric tree. The BFS approach is quite similar. The minor difference is the order of adding nodes to the queue.
这篇关于Same Tree的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-20RabbitMQ教程:新手入门指南
- 2024-11-20Redis教程:新手入门指南
- 2024-11-20SaToken教程:新手入门指南
- 2024-11-20SpringBoot教程:从入门到实践
- 2024-11-20Java全栈教程:从入门到实战
- 2024-11-20Java微服务系统教程:入门与实践指南
- 2024-11-20Less教程:初学者快速上手指南
- 2024-11-20MyBatis教程:新手快速入门指南
- 2024-11-20QLExpress教程:初学者快速入门指南
- 2024-11-20订单系统教程:从入门到实践的全面指南