二叉树结构
// 构造函数实现
function TreeNode(val) {
this.val = val;
this.left = null;
this.right = null;
}
// class 实现
class TreeNode() {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}
- 二叉树的遍历
//测试数据:二叉树结构如下:
var root = {
val: 1,
left: {
val: 2,
left: {
val: 4,
},
right: {
val: 5
}
},
right: {
val: 3,
left: {
val: 6,
},
right: {
val: 7
}
}
}
// 前序遍历 (根左右)
let result = [];
function DLR(root) {
console.log(root.val);
result.push(root.val);
if(root.left) DLR(root.left);
if(root.right) DLR(root.right);
}
// 中序遍历 (左根右)
function LDR(root) {
if(root.left) DLR(root.left);
console.log(root.val);
if(root.right) DLR(root.right);
}
// 后序遍历 (左右根)
function LDR(root) {
if(root.left) DLR(root.left);
if(root.right) DLR(root.right);
console.log(root.val);
}
// 层序遍历(也称为广度遍历,一层一层往下找)
function levelTraversal(root) {
if(!root) return false; // 如果头节点为空,返回为假
var result = [], tree = []; // tree是存放二叉树的结果
tree.push(root);
while(tree.length) {
var node = tree.shift(); // 将数组第一个节点放到node中
result.push(node.val); // 读取当前节点的val到result中
if(node.left) {
tree.push(node.left);
}
if(node.right) {
tree.push(node.right);
}
}
return result;
}