<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
/*
* function TreeNode(x) {
* this.val = x;
* this.left = null;
* this.right = null;
* }
*/
/**
*
* @param root TreeNode类 the root of binary tree
* @return int整型二维数组
*/
function threeOrders(root) {
// write code here
let preArray = [],
middleArray = [],
postArray = [];
function preOrder(root) {
if (root) {
preArray.push(root.val)
preOrder(root.left)
preOrder(root.right)
}
}
function inOrder(root) {
if (root) {
inOrder(root.left)
middleArray.push(root.val)
inOrder(root.right)
}
}
function postOrder(root) {
if (root) {
postOrder(root.left)
postOrder(root.right)
postArray.push(root.val)
}
}
preOrder(root)
inOrder(root)
postOrder(root)
return [preArray, middleArray, postArray]
}
module.exports = {
threeOrders: threeOrders
};
//———————————————————————————————迭代法———————————————————————————————————————
/*
* function TreeNode(x) {
* this.val = x;
* this.left = null;
* this.right = null;
* }
*/
/**
*
* @param root TreeNode类 the root of binary tree
* @return int整型二维数组
*/
function threeOrders(root) {
// write code here
//if(!root) return 0
// return 1+Math.max(MaxDep(root.left),(MaxDep(root.rigth))
let preArray = [],
midArry = [],
posArry = []
// 1.前序遍历、迭代法
function preorder(root) {
const res = []
if (root == null) return res
const stack = []
stack.push(root)
// preArray=root
while (stack.length > 0) {
const current = stack.pop()
res.push(current.val)
if (current.right !== null) stack.push(current.right)
if (current.left !== null) stack.push(current.left)
}
preArray = res
//
}
function midorder(root) {
const res = []
if (root == null) return res
const stack = []
stack.push(root)
while (stack.length > 0) {
const current = stack.pop()
if (current.right !== null) stack.push(current.right)
res.push(current.val)
if (current.left !== null) stack.push(current.left)
}
midArry = res
//
}
function postorder(root) {
const res = []
if (root == null) return res
const stack = []
stack.push(root)
while (stack.length > 0) {
const current = stack.pop()
if (current.right !== null) stack.push(current.right)
res.push(current.val)
if (current.left !== null) stack.push(current.left)
}
posArry = res
//
}
preorder()
midorder()
postorder()
return [preArray, midArry, posArry]
}
module.exports = {
threeOrders: threeOrders
};
</script>
</body>
</html>