题解 | #实现二叉树先序,中序和后序遍历#
实现二叉树先序,中序和后序遍历
http://www.nowcoder.com/practice/a9fec6c46a684ad5a3abd4e365a9d362
/*
* function TreeNode(x) {
* this.val = x;
* this.left = null;
* this.right = null;
* }
*/
/**
*
* @param root TreeNode类 the root of binary tree
* @return int整型二维数组
*/
let pre = [];
let mid = [];
let post = [];
function threeOrders( root ) {
if (root != null) {
preorder(root);
midorder(root);
postorder(root);
}
const res = [pre, mid, post];
return res;
}
function preorder(root) {
if (root == null) {
return;
}
pre.push(root.val);
preorder(root.left);
preorder(root.right);
}
function midorder(root) {
if (root == null) {
return;
}
midorder(root.left);
mid.push(root.val);
midorder(root.right);
}
function postorder(root) {
if (root == null) {
return;
}
postorder(root.left);
postorder(root.right);
post.push(root.val);
}
module.exports = {
threeOrders : threeOrders
};