二叉树的先中后序遍历
169 字
1 分钟
二叉树的先中后序遍历
先序遍历 根左右
递归
var preorderTraversal = function(root) { const res = [] const dfs = (root) => { if(root === null) return res.push(root.val) dfs(root.left) dfs(root.right) } dfs(root) return res};栈
var preorderTraversal = function(root) { if (!root) return; const res = [] const stack = [root]; while (stack.length > 0) { const node = stack.pop(); res.push(node.val) // 注意:因为栈是LIFO,所以先压入右子节点,再压入左子节点 if (node.right) stack.push(node.right); if (node.left) stack.push(node.left); } return res};中序遍历 左根右
递归
var inorderTraversal = function(root) { const res = [] const dfs = (root) => { if(root === null) return dfs(root.left) res.push(root.val) dfs(root.right) } dfs(root) return res};后序遍历 左右根
递归
var postorderTraversal = function(root) { const res = [] const dfs = (root) => { if(root === null) return dfs(root.left) dfs(root.right) res.push(root.val) } dfs(root) return res};文章分享
如果这篇文章对你有帮助,欢迎分享给更多人!
相关文章智能推荐
1
树的深度优先和广度优先遍历
算法以看书为例理解树的深度优先遍历(DFS)和广度优先遍历(BFS),以及 JavaScript 实现。
2
树
算法数组和链表是所有数据结构的基础。
3
102. 二叉树的层序遍历
算法思路就是用BFS(广度优先遍历),用嵌套数组携带层级信息用于判断是哪一层
4
K8s 核心概念图解:从一家汉堡店开始
随笔一份可交互的 Kubernetes 入门图解:集群、Pod、工作负载、Service、Ingress、Helm、镜像仓库,点一点就能看懂请求怎么流转。
5
链表
算法数组:增删非首尾元素往往需要移动元素。比如说在数组中间加一个元素,那么这个元素之后的元素都被向后移了一位。删除则是前移。
随机文章随机推荐














