我的个人小站链接:王大龙的个人小站。
面试题7:重建二叉树
题目:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
解题思路:这题的大问题和小问题都是一样的,都是先找出根结点,然后再对左边的节点和右边的节点分别进行处理。所以使用递归的方法。
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
index = tin.index(pre[0])
left = tin[:index]
right = tin[index+1:]
root = TreeNode(tin[index])
root.left = self.reConstructBinaryTree(pre[1:1+len(left)],left)
root.right = self.reConstructBinaryTree(pre[-len(right):],right)
return root
代码思路:首先构造树的结点类,然后就是用递归的思想去做了,递归出口就是当pre和tin为空。
面试题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 pNode == None:
return None
if pNode.right != None:
pNode = pNode.right
while pNode.left != None:
pNode = pNode.left
return pNode
while pNode.next != None:
proot = pNode.next
if(proot.left == pNode):
return proot
pNode = proot
return None
代码思路:首先排除特殊情况(不存在二叉树),然后就按解题思路中的情况依次写下来。