JS重建二叉树

重建二叉树的前置知识:

1. 遍历二叉树:

(1)前序遍历:根左右 –> 先访问根节点,再前序遍历左子树,最后前序遍历右子树;

(2)中序遍历:左根右 –> 先中序遍历左子树,再访问根节点,最后中序遍历右子树。

(3)后序遍历:左右根 –> 先后序遍历左子树,再后序遍历右子树,组后访问根节点。

2. 重建二叉树:

(1)前序+中序:前序遍历序列和中序遍历序列可以确定唯一的二叉树

 function TreeNode(x) {
    this.val = x;
    this.left = null;
    this.right = null;
}
function reConstructBinaryTree(pre, vin)
{
    if(pre.length === 0 || vin.length === 0){
        return null;
    }
    //创建根节点,根节点是前序遍历的第一个数
    var root = pre[0];
    var tree = new TreeNode(root);
    //找到中序遍历根节点所在位置
    var index = vin.indexOf(root);
    //对于中序遍历,根节点左边的节点即左子树,根节点右边的节点即右子树
    tree.left = reConstructBinaryTree(pre.slice(1,index+1),vin.slice(0,index));
    tree.right = reConstructBinaryTree(pre.slice(index+1),vin.slice(index+1));
    return tree;
}

测试:
pre='abdecf'
vin='dbeacf'
t=reConstructBinaryTree(pre,vin)
console.log(t);
输出:
TreeNode {
  val: 'a',
  left: 
   TreeNode {
     val: 'b',
     left: TreeNode { val: 'd', left: null, right: null },
     right: TreeNode { val: 'e', left: null, right: null } },
  right: 
   TreeNode {
     val: 'c',
     left: null,
     right: TreeNode { val: 'f', left: null, right: null } } }
[Finished in 0.9s]

(2)中序+后序:中序遍历序列和后序遍历序列可以确定唯一的二叉树

 function TreeNode(x) {
    this.val = x;
    this.left = null;
    this.right = null;
}
function reConstructBinaryTree(pos, vin)
{
    if(!pos || vin.length === 0){
        return null;
    }
    //创建根节点,根节点是后序遍历的最后一个数
    var root = pos[pos.length-1];
    var tree = new TreeNode(root);
    //找到中序遍历根节点所在位置
    var index = vin.indexOf(root);
    //对于中序遍历,根节点左边的节点即左子树,根节点右边的节点即右子树
    tree.left=reConstructBinaryTree(pos.slice(0,index),vin.slice(0,index))
    tree.right=reConstructBinaryTree(pos.slice(index,pos.length-1),vin.slice(index+1))
    return tree;
}

测试:
vin='dbeacf'
pos='debfca'
p=reConstructBinaryTree(pos,vin)
console.log(p);

输出:
TreeNode {
  val: 'a',
  left: 
   TreeNode {
     val: 'b',
     left: TreeNode { val: 'd', left: null, right: null },
     right: TreeNode { val: 'e', left: null, right: null } },
  right: 
   TreeNode {
     val: 'c',
     left: null,
     right: TreeNode { val: 'f', left: null, right: null } } }
[Finished in 0.6s]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值