二叉树相关面试的集锦(四)
一、二叉树中最远两个节点之间的距离
int _MaxDistance() { int maxdistance = 0; MaxDistance(_root, maxdistance); return maxdistance; }
//时间复杂度为O(N)
template<class T> int BinaryTree<T>::MaxDistance(Node* root, int& distance) { if (root == NULL) return 0; int LeftHight = MaxDistance(root->_LeftChild, distance); int RightHight = MaxDistance(root->_RightChild, distance); distance = distance > (LeftHight + RightHight) ? distance : (LeftHight + RightHight); return 1 + (LeftHight > RightHight ? LeftHight : RightHight); }
二、前序,中序创建二叉树
void _CreatByPrevOrderInOrder(char* arr1,char* arr2,size_t size) { assert(arr1 && arr2); _root = CreatByPrevOrderInOrder(arr1, arr2, size); } template<class T> BinaryTreeNode<T>* BinaryTree<T>::CreatByPrevOrderInOrder(char* arr1, char* arr2, size_t size) { if (size) { Node* root = new Node(arr1[0]); size_t index = 0; for (;; ++index) { if (arr2[index] == arr1[0]) break; } root->_LeftChild = CreatByPrevOrderInOrder(arr1+1, arr2, index); root->_RightChild = CreatByPrevOrderInOrder(arr1 + index + 1, arr2 + index + 1, size - index - 1); return root; } return NULL; }
三、中序,后序创建二叉树
void _CreatByInOrderOrderPost(char* arr1, char* arr2, size_t size) { assert(arr1 && arr2); _root = CreatByInOrderPostOrder(arr1, arr2, size); } template<class T> BinaryTreeNode<T>* BinaryTree<T>::CreatByInOrderOrderPost(char* arr1, char* arr2, size_t size) { if (size) { Node* root = new Node(arr2[size - 1]); size_t index = 0; for (;; ++index) { if (arr1[index] == arr2[size - 1]) break; } root->_LeftChild = CreatByInOrderOrderPost(arr1,arr2,index); root->_RightChild = CreatByInOrderOrderPost(arr1 + index + 1, arr2 + index, size - index - 1); return root; } return NULL; }
四、判断一个序列是不是二叉搜索树的后序遍历
template<class T> bool BinaryTree<T>::IsSearchBinaryTreePostOrder(char* arr, size_t size) { if (size > 1) { size_t index = 0; while (arr[index] < arr[size - 1]) { index++; } for (int i = index; i < size - 1; ++i) { arr[index] < arr[size - 1]; return false; } return IsSearchBinaryTreePostOrder(arr, 3) && IsSearchBinaryTreePostOrder(arr + index, size - index - 1); } return true; }