See this from my Blog https://dyingdown.github.io/2021/08/30/The-last-Internal-Node-of-a-Complete-Binary-Tree/
This problem derives from Heap Sort.
When you start to build the heap, you should start with the last internal node of the tree. And the index is usually N 2 − 1 \frac{N}{2} - 1 2N−1, N is the total length of the array.
But why is that ?
Complete Binary Tree
First, you need to know that when representing a tree using array, the tree is a Complete Binary Tree. See the following picture.
The nodes in the array are stored like this: [A, B, C, D, E, F, G, H, I, J]
And the number of nodes N N N can be represent as 2 0 + 2 1 + … + 2 k + s 2^{0}+2^{1}+\ldots +2^{k}+s 20+21+…+2k+s. ( k = d e p t h − 1 k = depth - 1 k=depth−1, s s s is the number of nodes in the deepest layer)
Proof
I’m proving this in a graphical layer.
First, let’s complete the tree to make it a Full Binary Tree.
As we can see, before completion, the last internal node is E E E.
Index of E E E = N N N - Red_Nodes - Deepest_Layer_Nodes
Let’s solve one by one.
-
Deepest_Layer_Nodes( s s s):
N = 2 0 + 2 1 + … + 2 k + s ⇒ s = N − 2 0 − 2 1 − ⋯ − 2 k N=2^{0}+2^{1}+\ldots +2^{k}+s \\\\ \Rightarrow s=N-2^{0}-2^{1}- \cdots -2^{k} \\ N=20+21+…+2k+s⇒s=N−20−21−⋯−2k
k + 1 k + 1 k+1 is the depth of the tree. s -
Red_Nodes( R )
As seen from the graph, number of red nodes is relative with the gray nodes.
Assume F F F is number of nodes of Full Binary Tree, D D D is the number of Gray Nodes.
F = 2 0 + 2 1 + … + 2 k + 1 D = F − N F=2^{0}+2^{1}+\ldots +2^{k+1}\\\\ D=F-N F=20+21+…+2k+1D=F−N
From the previous graph we can see that when D is odd, R = ( D − 1 ) / 2 R = (D - 1) / 2 R=(D−1)/2
Now let’s see another graph, when the number of gray nodes is even.
When D is even, R = D / 2 R = D / 2 R=D/2
∴ R = f l o o r ( D / 2 ) \therefore R = floor(D / 2) ∴R=floor(D/2)
-
Then E = 2 0 + … + 2 k − R E=2^{0}+\ldots +2^{k}-R E=20+…+2k−R
$\because R=floor\left( \dfrac{\left( 2^{0}+\ldots +2^{k+1}-N\right) }{2}\right) $
= f l o o r ( 1 2 + 2 0 + … + 2 k − N 2 ) = f l o o r ( 1 2 ) + f l o o r ( 2 0 + … + 2 k ) − f l o o r ( N 2 ) =floor\left( \dfrac{1}{2}+2^{0}+\ldots +2^{k}-\dfrac{N}{2}\right) =floor\left( \dfrac{1}{2}\right) +floor\left( 2^{0}+\ldots +2^{k}\right) -floor\left( \dfrac{N}{2}\right) =floor(21+20+…+2k−2N)=floor(21)+floor(20+…+2k)−floor(2N)
= 2 0 + … + 2 k − f l o o r ( N 2 ) =2^{0}+\ldots +2^{k}-floor\left(\dfrac{N}{2}\right) =20+…+2k−floor(2N)
∴ E = f l o o r ( N 2 ) \therefore E=floor\left(\dfrac{N}{2}\right) ∴E=floor(2N)
-
Because the index started from 0, so E = f l o o r ( N 2 ) − 1 E = floor\left(\dfrac{N}{2}\right) - 1 E=floor(2N)−1