JavaScript数据结构 ---- 二叉树
二叉树遍历
- 前序遍历:根左右
- 中序遍历:左根右
- 后序遍历:左右根
记忆:根的位置决定什么顺序,左一定在右的前边。
树结构
function TreeNode(val){
this.val = val;
this.left = null;
this.right = null;
}
前序递归
function preOrder(root){
if(root == null){
return
}
console.log(root.val);
preOrder(root.left);
preOrder(root.right);
中序递归
function preOrder(root){
if(root == null){
return
}
preOrder(root.left);
console.log(root.val);
preOrder(root.right);
后序递归
function preOrder(root){
if(root == null){
return
}
preOrder(root.left);
preOrder(root.right);
console.log(root.val);
var isSymmetric = function(root) {
if(root == null){
return true
}
const dfs = function(left,right){
if(left==null && right==null){
return true
}
if(left==null || right==null || left.val!==right.val){
return false
}
return dfs(left.left,right.right)&&dfs(left.right,right.left)
}
return dfs(root.left,root.right)
};
后序递归
function preOrder(root){
if(root == null){
return
}
preOrder(root.left);
preOrder(root.right);
console.log(root.val);
深度搜索DFS
应用题型:满足(最大,最小,某种要求)的深度、路径、节点和…
function dfsTemplate(root){
//存储最终结果
let res;
//初始化当前结果
let start;
//构造递归函数,通常参数为当前节点和当前结果
let dfs = function(node, currentResult){
//终止条件时返回
if(node == null){
return
}
//更新当前结果currentResult
//若到达末尾叶子结点,进行最优结果更新
if(node.left == null && node.right == null){
//update res
}
//左右子树递归
dfs(node.left, currentResult);
dfs(node.right, currentResult);
}
dfs(root, start);
return res
var minDepth = function(root) {
//存储最终结果
let res = 0;
//初始化当前结果
let start = 0;
//构造递归函数dfs,通常参数为当前节点和当前结果
let dfs = function (node, currentResult) {
//终止条件返回判断
if (node == null) {
return;
}
//更新当前结果currentResult
currentResult++
//若到达末尾叶子结点,进行最优结果更新
if (node.left == null && node.right == null) {
//update res
if(res>currentResult||res ==0){
res = currentResult
}
}
//左右子树递归
dfs(node.left, currentResult);
dfs(node.right, currentResult);
}
dfs(root, start);
return res;
};
//求最大高度,因此要从下往上进行遍历。判断左右差是否小于2
var isBalanced = function(root) {
let res = true;
let dfs = function(node) {
if(node == null){
return 0
}
// 提前返回
if (!res) return;
//求最大高度,因此是从下往上为后序遍历.
let leftMax = dfs(node.left);
let rightMax = dfs(node.right);
//判断高度值相差是否超过1.
if(Math.abs(leftMax-rightMax)>1){
res = false;
}
return 1+Math.max(leftMax,rightMax)
}
dfs(root);
return res
};
广度搜索BFS
持续更新
参考文献
https://github.com/ligecarryme/algorithm-pattern-JavaScript
https://www.bilibili.com/video/BV1MF41147Ga/spm_id_from=333.788&vd_source=6789cf798176f93af6623f43499dd892
https://www.bilibili.com/video/BV1Qa411t7NA/spm_id_from=333.788&vd_source=6789cf798176f93af6623f43499dd892