面试题7:重建二叉树
题目描述:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
详细代码:
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回构造的TreeNode根节点
def reConstructBinaryTree(self, pre, tin):
# write code here
if not pre or not tin:
return None
root = TreeNode(pre[0])
val = tin.index(pre[0])
root.left = self.reConstructBinaryTree(pre[1:val+1], tin[:val])
root.right = self.reConstructBinaryTree(pre[val+1: ], tin[val+1: ])
return root
面试题8:二叉树的下一个节点
题目描述:给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
详细代码:
# -*- coding:utf-8 -*-
# class TreeLinkNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# self.next = None
class Solution:
def GetNext(self, pNode):
# write code here
if not pNode:
return None
#若这个节点有右子树,则下一节点是右子树的最左节点
elif pNode.right != None:
pNode = pNode.right
while pNode.left != None:
pNode = pNode.left
return pNode
#若这个节点无右子树,且是父节点的右节点,则若找到一个节点是其父节点的左节点,那么下一节点是此节点的父节点
elif pNode.next != None and pNode.next.right == pNode: #pNode.next代表父节点
while pNode.next != None and pNode.next.left != pNode:
pNode = pNode.next
return pNode.next
#若这个节点无右子树,且是父节点的左节点,则下一节点是它的父节点
else:
return pNode.next