探索部分 二叉树
(1)二叉树的遍历
递归方法
function TreeNode (val) {
this.val = val
this.left = this.right = null
}
//定义一个二叉树 [1,null,2,3]
var root = new TreeNode(1)
var rootr = new TreeNode(2)
var rootrl = new TreeNode(3)
root.left = null
root.right = rootr
rootr.left = rootrl
rootr.right = null
rootrl.left = null
rootrl.right = null
//递归版本
// 前序遍历
var preorderTraversal = function (root) {
if (root) {
console.log(root.val)
preorderTraversal(root.left)
preorderTraversal(root.right)
}
}
// 中序遍历
var inorderTraversal = function (root) {
if (root) {
inorderTraversal(root.left)
console.log(root.val)
inorderTraversal(root.right)
}
}
// 后续遍历
var postorderTraversal = function (root) {
if (root) {
postorderTraversal(root.left)
postorderTraversal(root.right)
console.log(root.val)
}
}
preorderTraversal(root) // 1 2 3
inorderTraversal(root) //1 3 2
postorderTraversal(root) //3 2 1
非递归方法
function TreeNode (val) {
this.val = val;
this.left = this.right = null;
}
var root = new TreeNode(1);
var rootr = new TreeNode(2);
var rootrl = new TreeNode(3);
root.left = null;
root.right = rootr;
rootr.left = rootrl;
rootr.right = null;
rootrl.left = null;
rootrl.right = null;
var preorderTraversal = function (root) {
if (root === null) return []
var stack = [];
stack.push(root)
var res = [];
while (stack.length != 0) {
var node = stack.pop();
if (node != null) {
res.push(node.val)
stack.push(node.right)
stack.push(node.left)
}
}
return res
};
var inorderTraversal = function (root) {
if (root === null) return []
var stack = [];
var res = [];
var node = root;
while (stack.length != 0 || node) {
if (node != null) {
stack.push(node);
node = node.left;
}
else {
node = stack.pop()
res.push(node.val)
node = node.right;
}
}
return res
};
var postorderTraversal = function (root) {
var stack = [root];
var res = [];
var node = root;
while (stack.length != 0) {
var tmp = stack[stack.length - 1];
if (tmp.left != null && node != tmp.left && node != tmp.right) {
stack.push(tmp.left);
}
else if (tmp.right != null && node != tmp.right) {
stack.push(tmp.right);
}
else {
var r = stack.pop();
res.push(r.val)
node = tmp;
}
}
return res;
};
var preorder = preorderTraversal(root)
console.log(preorder);
var inorder = inorderTraversal(root)
console.log(inorder)
var postorder = postorderTraversal(root)
console.log(postorder)
层次遍历
var leveOrderTranversal = function (root) {
var queue = []
var res = []
queue.push(root)
while (queue.length != 0) {
var node = queue.shift()
res.push(node.val)
if (node.left != null) queue.push(node.left)
if (node.right != null) queue.push(node.right)
}
return res
}
序列化和反序列化