JavaScript 结题(普通解法)
实现二叉树先序,中序和后序遍历
http://www.nowcoder.com/questionTerminal/a9fec6c46a684ad5a3abd4e365a9d362
JavaScript 结题(普通解法)
/*
* 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 === null) {
return [];
}
var result = [];
result.push(preTravesal(root));
result.push(inTravesal(root));
result.push(postTravesal(root));
return result;
}
function preTravesal(root, result = []) {
if (root !== null) {
result.push(root.val);
preTravesal(root.left, result);
preTravesal(root.right, result);
}
return result;
}
function inTravesal(root, result = []) {
if (root !== null) {
inTravesal(root.left, result);
result.push(root.val);
inTravesal(root.right, result);
}
return result;
}
function postTravesal(root, result = []) {
if (root !== null) {
postTravesal(root.left, result);
postTravesal(root.right, result);
result.push(root.val);
}
return result;
}
module.exports = {
threeOrders : threeOrders
};
查看16道真题和解析