面试题5:计算二叉树中最大节点到最小节点之间的距离
网易2016实习研发工程师编程题
有一棵二叉树,树上每个点标有权值,权值各不相同,请设计一个算法算出权值最大的叶节点到权值最小的叶节点的距离。二叉树每条边的距离为1,一个节点经过多少条边到达另一个节点为这两个节点之间的距离。
给定二叉树的根节点root,请返回所求距离。
1 #include <iostream> 2 #include <climits> 3 //struct ListNode { 4 // int val; 5 // ListNode* next; 6 // ListNode() : 7 // val(0), next(nullptr) { 8 // } 9 // ListNode(int x) : 10 // val(x), next(nullptr) { 11 // } 12 //}; 13 14 struct TreeNode { 15 int val; 16 TreeNode* left; 17 TreeNode* right; 18 TreeNode() : 19 val(0), left(nullptr), right(nullptr) { 20 } 21 TreeNode(int x) : 22 val(x), left(nullptr), right(nullptr) { 23 } 24 }; 25 26 class Solution { 27 private: 28 TreeNode* maxNode = new TreeNode(INT_MIN); 29 TreeNode* minNode = new TreeNode(INT_MAX); 30 private: 31 TreeNode* getLCANode(TreeNode* root, TreeNode* p, TreeNode* q) { 32 if (root == nullptr || root == p || root == q) { 33 return root; 34 } 35 TreeNode* left = getLCANode(root->left, p, q); 36 TreeNode* right = getLCANode(root->right, p, q); 37 if (left && right) { 38 return root; 39 } 40 if (left == nullptr) 41 return right; 42 else // right == nullptr; 43 return left; 44 } 45 46 void getMaxMinNode(TreeNode* root){ 47 if(root==nullptr) return; 48 if(root->val > maxNode->val){ 49 maxNode = root; 50 } 51 if(root->val < minNode->val){ 52 minNode = root; 53 } 54 getMaxMinNode(root->left); 55 getMaxMinNode(root->right); 56 } 57 58 //get distance between maxNode or minNode and LCAnode 59 int getDis(TreeNode* LCANode,TreeNode* node){ 60 if(LCANode == nullptr) return -1; 61 if(LCANode->val == node->val) 62 return 0; 63 int dis = getDis(LCANode->left,node); 64 if(dis == -1){ 65 dis = getDis(LCANode->right,node); 66 } 67 if(dis != -1){ 68 return dis + 1; 69 } 70 return -1; 71 } 72 public: 73 int getMaxMinNodeDis(TreeNode* root){ 74 if(root == nullptr) return 0; 75 getMaxMinNode(root); 76 TreeNode* LCANode = getLCANode(root,maxNode,minNode); 77 int a = getDis(LCANode,maxNode); 78 int b = getDis(LCANode,minNode); 79 return a+b; 80 } 81 };