二叉树的前序,中序,后序遍历,树的深度优先搜索,广度优先搜索

65 阅读1分钟
function Node(value){
    this.value = value
    this.left = null //左子树
    this.right = null //右子树
}
let a = new Node('a')
let b = new Node('b')
let c = new Node('c')
let d = new Node('d')
let e = new Node('e')
let f = new Node('f')
a.left = b
a.right = c
b.left = d
b.right = e
c.left = f
// 二叉树的前序遍历
function front(root){
    if(!root) return
    console.log(root.value)
    front(root.left)
    front(root.right)
}
front(a)
二叉树的中序遍历
function middle(root){
    if(!root) return
    middle(root.left)
    console.log(root.value)
    middle(root.right)
}
middle(a)
// 二叉树的后序遍历
function end(root){
    if(!root) return
    end(root.left)
    end(root.right)
    console.log(root.value)
}
end(a)
//二叉树的深度优先搜索
function dfs(root,target){
    if(!root) return false
    if(root.value == target) return true
    let left = dfs(root.left,target)
    let right = dfs(root.right,tar)
    return left || right //如果左右子树都没有找到就返回空
}
// 深拷贝
function deepClone(obj) {
  let res = {};
  let deep = {};
  if (!obj) return;
  for (let key in obj) {
    if (isObject(obj[key])) {
      deep[key] = deepClone(obj[key]);
    } else if (isArray(obj[key])) {
      res[key] = obj[key];
    } else {
      res[key] = obj[key];
    }
  }
  return Object.assign(res, deep);
}
function isArray(obj) {
  return Object.prototype.toString.call(obj) === "[object Array]";
}
function isObject(obj) {
  return Object.prototype.toString.call(obj) === "[object Object]";
}