当前位置: 首页 > news >正文

【前端面试】leetcode树javascript

写一个树

// 定义二叉树节点
function TreeNode(val, left, right) {this.val = (val === undefined ? 0 : val)this.left = (left === undefined ? null : left)this.right = (right === undefined ? null : right)
}// 示例使用
const root = new TreeNode(1,new TreeNode(2,new TreeNode(4),new TreeNode(5)),new TreeNode(3,null,new TreeNode(7))
);

二叉树的中序遍历

https://leetcode.cn/problems/binary-tree-inorder-traversal/description/
在这里插入图片描述

递归

/*** Definition for a binary tree node.* function TreeNode(val, left, right) {*     this.val = (val===undefined ? 0 : val)*     this.left = (left===undefined ? null : left)*     this.right = (right===undefined ? null : right)* }*/
/*** @param {TreeNode} root* @return {number[]}*/
var inorderTraversal = function(root) {const res = [];const inorder = (root) => {if (!root) {return;}inorder(root.left);res.push(root.val);inorder(root.right);}inorder(root);return res;
};

二叉树的先序遍历

var inorderTraversal = function(root) {const res = [];const inorder = (root) => {if (!root) {return;}res.push(root.val);inorder(root.left);inorder(root.right);}inorder(root);return res;
};

二叉树的后序遍历

var inorderTraversal = 

http://www.mrgr.cn/news/19072.html

相关文章:

  • 【IPV6从入门到起飞】2-1 获取你的IPV6(手机、CPE等)
  • opencv简单介绍
  • ARM汇编
  • 一阶微分方程的解的存在唯一性定理
  • BaseCTF-week2-wp
  • zdppy+vue3+onlyoffice文档管理系统实战 20240903 上课笔记 登录功能完成
  • 【C++】C++智能指针详解
  • 函数的力量:掌握Python中的“返回值”艺术
  • 【60天备战软考高级系统架构设计师——第七天:架构风格】
  • kafka基础知识(持续更新中~)
  • 单端输入与差分输入
  • 标准库标头 <optional> (C++17)学习之optional
  • redis之缓存淘汰策略
  • tcp udp
  • HTB-bike(SSTI模版注入)
  • Loadrunner12录制时,目标网站打不开的解决办法
  • Phalcon 增删改查的搭建过程
  • Kotlin 流 Flow
  • 数据恢复工具,电脑+手机双端,十分好用!
  • 智能提醒助理系列-一阶段推广心得1