# Interview question 7: reconstruction of binary tree

Topic Description: input the results of the preorder traversal and inorder traversal of a binary tree, please reconstruct the binary tree. It is assumed that the results of the input preorder traversal and preorder traversal do not contain duplicate numbers. For example, if the sequence {1,2,4,7,3,5,6,8} and the sequence {4,7,2,1,5,3,8,6} are input, the binary tree will be reconstructed and returned.

Detailed code:

```# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
# Returns the TreeNode root node of the construct
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
```

# Interview question 8: next node of binary tree

Topic Description: given a binary tree and one of its nodes, please find the next node in the middle order traversal order and return. Note that the nodes in the tree contain not only left and right child nodes, but also pointers to the parent nodes.

Detailed code:

```# -*- coding:utf-8 -*-
#     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

#If this node has a right subtree, the next node is the leftmost node of the right subtree
elif pNode.right != None:
pNode = pNode.right
while pNode.left != None:
pNode = pNode.left
return pNode

#If this node has no right subtree and is the right node of the parent node, if a node is found to be the left node of its parent node, then the next node is the parent node of this node
elif pNode.next != None and pNode.next.right == pNode:    #pNode.next represents the parent node
while pNode.next != None and pNode.next.left != pNode:
pNode = pNode.next
return pNode.next

#If this node has no right subtree and is the left node of the parent node, the next node is its parent node
else:
return pNode.next

```

Posted by Wozzr on Sun, 01 Dec 2019 13:38:17 -0800