登录
首页 >  文章 >  前端

如何使用 Javascript 确定二叉树是否相同

来源:dev.to

时间:2024-08-22 17:09:47 305浏览 收藏

编程并不是一个机械性的工作,而是需要有思考,有创新的工作,语法是固定的,但解决问题的思路则是依靠人的思维,这就需要我们坚持学习和更新自己的知识。今天golang学习网就整理分享《如何使用 Javascript 确定二叉树是否相同》,文章讲解的知识点主要包括,如果你对文章方面的知识点感兴趣,就不要错过golang学习网,在这可以对大家的知识积累有所帮助,助力开发能力的提升。

如何使用 Javascript 确定二叉树是否相同

介绍

这里相同意味着结构和值都处于相同的位置。

为了实现这一点,我们需要使用 dfs 算法,这样它也会检查深度。

使用 bfs 算法无法实现这一点。

所以这里我使用有序遍历来得到结果

class Node {
    constructor(data)
    {
        this.left = null;
        this.right = null;
        this.data = data;
    }
}

let root1, root2;

// left root right
const 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

*/

有任何问题请随时联系我

今天关于《如何使用 Javascript 确定二叉树是否相同》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:dev.to 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>