Skip to content

Commit

Permalink
feat: 从上到下打印二叉树 III
Browse files Browse the repository at this point in the history
  • Loading branch information
sl1673495 committed May 31, 2020
1 parent b03ed0c commit 73e6b31
Show file tree
Hide file tree
Showing 3 changed files with 91 additions and 5 deletions.
10 changes: 5 additions & 5 deletions 工具/二叉树.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
class TreeNode {
constructor(val) {
this.val = val
this.left = null
this.right = null
}
constructor(val) {
this.val = val
this.left = null
this.right = null
}
}

module.exports = TreeNode
47 changes: 47 additions & 0 deletions 栈和队列/二叉树的前序遍历-144.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
const TreeNode = require("../工具/二叉树")

/**
* @param {TreeNode} root
* @return {number[]}
*/
let preorderTraversal = function (root) {
let res = []
let stack = [
{
type: "go",
node: root,
},
]

while (stack.length) {
let { type, node } = stack.pop()

if (!node) continue

if (type === "print") {
res.push(node.val)
}

if (type === "go") {
stack.push({ type: "print", node })

if (node.right) {
stack.push({ type: "go", node: node.right })
}

if (node.left) {
stack.push({ type: "go", node: node.left })
}
}
}

return res
}

const tree = new TreeNode(1)
tree.left = new TreeNode(4)
tree.left.left = new TreeNode(5)
tree.right = new TreeNode(6)
tree.right.right = new TreeNode(7)

console.log(preorderTraversal(tree))
39 changes: 39 additions & 0 deletions 栈和队列/从上到下打印二叉树III-面试题32.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
const TreeNode = require("../工具/二叉树")

let levelOrder = function (root) {
let queue = [root]
let res = []
if (!root) return res
let level = 0
while (queue.length) {
level++
let subRes = []
let len = queue.length
let shouldReverse = level % 2 === 0

for (let i = 0; i < len; i++) {
let node = queue.shift()
subRes.push(node.val)
if (node.left) {
queue.push(node.left)
}
if (node.right) {
queue.push(node.right)
}
}
// 偶数行 把结果子数组reverse即可
if (shouldReverse) {
subRes.reverse()
}
res.push(subRes)
}
return res
}

let tree = new TreeNode(1)
tree.left = new TreeNode(2)
tree.left.left = new TreeNode(4)
tree.right = new TreeNode(3)
tree.right.right = new TreeNode(5)

console.log(levelOrder(tree))

0 comments on commit 73e6b31

Please sign in to comment.