
介绍
这里相同意味着结构和值都处于相同的位置。
为了实现这一点,我们需要使用 dfs 算法,这样它也会检查深度。
使用 bfs 算法无法实现这一点。
所以这里我使用有序遍历来得到结果
class Node { constructor(data) { this.left = null; this.right = null; this.data = data; }}let root1, root2;// left root rightconst checkIdentical = (binaryTree1, binaryTree2) => { let tree = ''; const helper = (root) => { if (root == null) { return tree; } helper(root.left); tree += root.data; helper(root.right); return tree; }; const tree1 = helper(binaryTree1); tree = ''; const tree2 = helper(binaryTree2); if (tree1 === tree2) { console.log('Both are identical'); } else { console.log('Not Identical'); }}root1 = new Node(1);root1.left = new Node(2);root1.right = new Node(3);root1.left.left = new Node(4);root1.left.right = new Node(5);root2 = new Node(1);root2.left = new Node(2);root2.right = new Node(3);root2.left.left = new Node(4);root2.left.right = new Node(5);checkIdentical(root1, root2);/*Both are identical*/
有任何问题请随时联系我
立即学习“Java免费学习笔记(深入)”;
以上就是如何使用 Javascript 确定二叉树是否相同的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1490765.html
微信扫一扫
支付宝扫一扫