ConardLi

二叉树简介

``````function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
}``````

题目1 二叉树遍历

1.1 题目描述

``````输入
ABC
BAC
FDXEAG
XDEFAG

BCA
XEDGAF``````

1.2 解题思路

1.前序遍历的头部为跟节点

2.中序遍历以跟节点分割，左侧为左子中序遍历，右侧为右子树中序遍历

3.根据中序遍历得到的左子树右子树的长度，得到左子树的前序遍历和右子树的前序遍历

1.3 代码

``````let pre;
let vin;

print(getHRD(pre,vin));
}

function getHRD(pre, vin) {
if (!pre) {
return '';
}
if (pre.length === 1) {
return pre;
}
const vinLeft = vin.substring(0, splitIndex);
const vinRight = vin.substring(splitIndex + 1);
const preLeft = pre.substring(1, splitIndex + 1);
const preRight = pre.substring(splitIndex + 1);
return getHRD(preLeft, vinLeft) + getHRD(preRight, vinRight) + head;``````

题目2 二叉树重建

2.3 代码

``````    function reConstructBinaryTree(pre, vin) {
if(pre.length === 0){
return null;
}
if(pre.length === 1){
return new TreeNode(pre[0]);
}
const value = pre[0];
const index = vin.indexOf(value);
const vinLeft = vin.slice(0,index);
const vinRight = vin.slice(index+1);
const preLeft = pre.slice(1,index+1);
const preRight = pre.slice(index+1);
const node = new TreeNode(value);
node.left = reConstructBinaryTree(preLeft, vinLeft);
node.right = reConstructBinaryTree(preRight, vinRight);
return node;
}``````

ConardLi

Reading makes a full man, conference a ready man, and writing an exact man.

9.5k 声望
2.3k 粉丝
0 条评论