面试题7:重建二叉树
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
主要使用递归的思想,在前序遍历的数组中最先出现的就是根节点,然后我们遍历中序序列,找到根节点的值,左边的就是左子树,递归求左子树的根节点,赋值给root.left;右边就是右子树,递归求右子树的根节点,赋值给root.right。
/* function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
} */
function reConstructBinaryTree(pre, vin)
{
let root= ConstructBinaryTree(pre,0,pre.length-1,vin,0,vin.length-1);
return root;
}
function ConstructBinaryTree(pre,preStartIndex,preEndIndex,vin,vinStartIndex,vinEndIndex){
if(preStartIndex>preEndIndex||vinStartIndex>vinEndIndex)
return null;
//从先序中得到根节点
let root=new TreeNode(pre[preStartIndex]);
//然后在中序中遍历,找到根节点的位置,左边是左子树,右边是右子树
for(let i=vinStartIndex;i<=vinEndIndex;i++){
if(pre[preStartIndex]===vin[i]){
//结束索引preStartIndex+i-vinStartIndex,刚好是左子树结束的位置
root.left=ConstructBinaryTree(pre,preStartIndex+1,preStartIndex+i-vinStartIndex,vin,vinStartIndex,i-1);
root.right=ConstructBinaryTree(pre,preStartIndex+i-vinStartIndex+1,preEndIndex,vin,i+1,vinEndIndex);
break;
}
}
return root;
}
面试题8:二叉树的下一个节点
给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
主要的解决思想
1.该节点有右子树,那么该节点的下一个节点就是右子树中最左的节点
2.该节点没有右子树,那么该节点的下一个节点就是,第一个当前节点是父节点左孩子的节点
function GetNext(pNode)
{
if(pNode===null)
return null;
// write code here
//如果该节点有右子树,那么该节点的下一个节点,就是右子树最左的节点
if(pNode.right){
let root=pNode.right;
while(root.left){
root=root.left;
}
return root;
}
//没右子树,则找第一个当前节点是父节点左孩子的节点,这里的next其实是parent
while(pNode.next){
if(pNode.next.left===pNode)
return pNode.next;
pNode = pNode.next;
}
return null;
}











网友评论