JavaScript实现数据结构 -- 树(二)

608 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路

本文主要记录了用JavaScript实现数据结构 -- 树、二叉树,以及二叉树的前、中、后序遍历。

二叉树

每个节点最多有两个子节点的树叫二叉树。 在这里插入图片描述

二叉树的常用操作

定义二叉树

	//定义二叉树
	const bt = {
	    val: 1,
	    left:{
	        val: 2,
	        left:{
	            val: 4,
	            left:null,
	            right:null
	        },
	        right:{
	            val: 5,
	            left:null,
	            right:null
	        }
	    },
	    right:{
	        val: 3,
	        left:{
	            val: 6,
	            left:null,
	            right:null
	        },
	        right:{
	            val: 7,
	            left:null,
	            right:null
	        }
	    }
	}

前序遍历

前序遍历过程

根 => 左 => 右 在这里插入图片描述

  • 访问根节点;
  • 对根节点的左子树进行前序遍历;
  • 对根节点的右子树进行前序遍历;

代码实现

用递归实现前序遍历:

	//前序遍历
	const preorder = (root) => {
	    if(!root){
	        return ;
	    }
	    console.log(root.val);
	    preorder(root.left);
	    preorder(root.right);
	}
	
	preorder(bt);

用栈实现前序遍历:

const preorder = (root) => {
    if(!root)return ;
    const stack = [root];
    while(stack.length){
        const n = stack.pop();
        console.log(n.val);
        if(n.right)stack.push(n.right);
        if(n.left)stack.push(n.left);
    }
}

preorder(bt);

在这里插入图片描述

中序遍历

中序遍历过程

左 =>根 => 右 在这里插入图片描述

  • 对根节点的左子树进行前序遍历;
  • 访问根节点;
  • 对根节点的右子树进行前序遍历;

代码实现

用递归实现中序遍历:

const inorder = (root) => {
    if(!root){
        return ;
    }
    inorder(root.left);
    console.log(root.val);
    inorder(root.right);
}

inorder(bt);

用栈实现中序遍历:

	const inorder = (root) => {
	    if(!root){
	        return ;
	    }
	    const stack = [];
	    let p = root;
	    while(stack.length || p){
	        while(p){
	            stack.push(p);
	            p = p.left;
	        }
	        const n = stack.pop();
	        console.log(n.val);
	        p = n.right;
	    }
	}
	
	inorder(bt);

在这里插入图片描述

后序遍历

后序遍历过程

左 => 右 => 根 在这里插入图片描述

  • 对根节点的左子树进行前序遍历;

  • 对根节点的右子树进行前序遍历;

  • 访问根节点;

代码实现

用递归实现后序遍历:

const postorder = (root) => {
    if(!root){
        return ;
    }
    postorder(root.left);
    postorder(root.right);
    console.log(root.val);
}

postorder(bt);

用栈实现后序遍历:

	const postorder = (root) => {
	    if(!root){
	        return ;
	    }
	    const outputstack = [];
	    const stack = [root];
	    while(stack.length){
	        const n = stack.pop();
	        outputstack.push(n);
	        if(n.left) stack.push(n.left);
	        if(n.right) stack.push(n.right);
	    }
	    while(outputstack.length){
	        const n = outputstack.pop();
	        console.log(n.val);
	    }
	}
	
	postorder(bt);

在这里插入图片描述

本文到此结束

如果大家还有什么其他想法,欢迎在评论区交流!