面经汇总(四)——数据结构和算法

链表:链表的每个节点分为两个部分,一是数据区域,用于存储元素的数据信息;二是指针域,用于存储其直接后继的节点信息,就是向下一个节点的地址,当当前节点为末节点时为null。

function ListNode(x){
    this.val = x;
    this.next = null;
}

二叉树:

 function TreeNode(x) {
    this.val = x;
    this.left = null;
    this.right = null;
}

二叉树遍历

广度优先搜索(BFS)/层序遍历

//二叉树的广度优先搜索BFS
//借助队列的数据形式
function PrintFromTopToBottom(root)
{
     write code here
    var list = []
    var result = []
    if(root) {list.push(root)}
    while(list.length != 0) {
        let node = list.shift()
        if(node.left) {
            list.push(node.left)
        }
        if(node.right) {
            list.push(node.right)
        }
        result.push(node.val)
    }
    return result
}

深度优先搜索(DFS)

栈方法

// 二叉树的深度优先搜素(前序遍历)
//使用栈,后入先出;先压入右子树,再压入左子树
function DFS(root) {
  var list = []
  var result = []
  if (root) {
    list.push(root)
  }
  while(list.length != 0) {
    let node = list.pop()
    if(node.right) {
      list.push(node.right)
    }
    if(node.left) {
      list.push(node.left)
    }
    result.push(node.val)
  }
  return result
}

递归方法

//节点结构
/* function TreeNode(x) {
    this.val = x;
    this.left = null;
    this.right = null;
} */

//1、前序遍历
function DLR(root){
    console.log(root.val);
    if(root.left){
        DLR(root.left);
    }
    if(root.right){
        DLR(root.right);
    }
}

//2、中序遍历
function LDR(root){
    if(root.left){
        LDR(root.left);
    }
    console.log(root.val);
    if(root.right){
        LDR(root.right);
    }
}

//3、后序遍历
function LRD(root){
    if(root.left){
        LRD(root.left);
    }
    if(root.right){
        LRD(root.right);
    }
    console.log(root.val);
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值