There is a tree, not necessarily a binary tree, with N nodes numbered 0 to n-1. There is an array A. The index of the array is 0 to n-1. The array value a [I] indicates the ID of the parent node of node I, and the parent node ID of the root node is-1. Given array A, the height of the tree is obtained. To analyze this question, we first write out the array and further analyze it. The following example shows: 333-12234:
A very direct solution is to traverse every element in array A and trace back to the root node to get the height of this node. After the array is traversed, the maximum value is the height of the tree. The process of the preceding example is as follows:
0-> 3->-1. The height from 0 to the root is 2. Similarly, 1-> 3->-1, 2-> 3->-1.
3->-1. The height is 1.
4-> 2-> 3->-1, get the height of 3
In summary, the maximum height is 3, and the height of the tree is 3. The time complexity of this method is O (n ^ 2), and the space complexity is O (1 ).
So can we continue to improve? Through the above calculation process, we can find that when 4-> 2-> 3->-1 is calculated, it is obvious that 2-> 3->-1 has been calculated, you do not need to waste time re-computing. The sample code is as follows:
Int getheight (vector <int> & tree, vector <int> & height, int index) // recursively calculates the height of the node index {If (tree [Index] =-1) return 0; If (height [Index]! =-1) return height [Index]; // return directly after calculation, improving the efficiency of int res = 1 + getheight (tree, height, tree [Index]); height [Index] = res; return res;} int treeheight (vector <int> & tree) {int I, length = tree. size (), maxheight = 0; If (length <= 0) return 0; vector <int> height (length,-1); for (I = 0; I <length; I ++) {If (height [I] =-1) {maxheight = max (maxheight, getheight (tree, height, I )); // If the node does not calculate the height, call calculation} return maxheight ;}
If you have any questions, please correct them. Thank you.
Height Analysis of the tree to be written