您的位置:首页 > 职场人生

二叉树遍历的所有递归和迭代实现

2016-06-16 02:33 423 查看
@[二叉树|排列|前序|中序|后序]

gitthub:https://github.com/1414648814

无论是在面试过程中还是实际项目中,我们都会遇见二叉树的遍历,当然这个只要了解了原理,其实很简单;

二叉树的排列包括(注意顺序)

* 前序排列:先遍历树的跟节点,然后是树的左子节点,再然后才是右子节点;

* 中序排列:先遍历树的左子节点,然后是跟节点,再然后才是右子节点;

* 后序排列:先遍历树的左子节点,然后是树的右子节点,再然后才是跟节点;

首先是节点的声明

function TreeNode(val) {
this.val = val;
this.left = this.right = null;
}


1.前序遍历

1.递归实现

核心思想:注意函数要分开写,因为这是个递归函数,不然要重新初始化数组了;

代码

/**
* @param {TreeNode} root
* @return {number[]}
*/
var preorderTraversal = function(root) {
var result = [];
preorder(root);
return result;

function preorder(root)
{
if (root === null) return;
result.push(root.val);
preorder(root.left);
preorder(root.right);
}
};


2.迭代实现

核心思想:原理类似,都是需要栈来实现,但是要注意第二个先遍历是因为栈是后进先出;

var preorderTraversal1 = function(root) {
var result = [];
var stack = [];

while (root || stack.length!== 0)
{
while (root)
{
stack.push(root);
result.push(root.val);
root = root.left;
}
root = stack[stack.length-1];
stack.pop();
root = root.right;
}

return result;
};

var preorderTraversal2 = function(root) {
var result = [];
var stack = [];
var cur = null;
stack.push(root);

while (cur = stack.pop())
{
result.push(cur.val);
if (cur.right)
stack.push(cur.right);
if (cur.left)
stack.push(cur.left);
}

return result;
};


2.中序遍历

1.递归实现

核心思想

var inorderTraversal = function(root) {
var result = [];
inorder(root);
return result;

function inorder(root)
{
if (root === null) return;
inorder(root.left);
result.push(root.val);
inorder(root.right);
}
};


2.迭代实现

核心思想

var inorderTraversal = function(root) {
var result = [];
var stack = [];

while (root || stack.length!== 0)
{
while (root)
{
stack.push(root);
root = root.left;
}
root = stack[stack.length-1];
result.push(root.val);
stack.pop();
root = root.right;
}

return result;
};


3.后序遍历

1.递归实现

核心思想

var postorderTraversal = function(root) {
var result = [];
postorder(root);
return result;

function postorder(root)
{
if (root === null) return;
postorder(root.left);
postorder(root.right);
result.push(root.val);
}
};


2.迭代实现

核心思想

var postorderTraversal1 = function(root) {
var result = [];
var stack = [];

while (root || stack.length!== 0)
{
while (root)
{
stack.push(root);
result.unshift(root.val);
root = root.right;
}
root = stack[stack.length-1];
stack.pop();
root = root.left;
}

return result;
};

var postorderTraversal2 = function(root) {
var stack = [];
var values = [];

if (root)
stack.push(root);

while(stack.length > 0) {
var node = stack.pop();

values.unshift(node.val);

if (node.left)
stack.push(node.left);

if (node.right)
stack.push(node.right);
}

return values;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息