Skip to content
Advertisement

Change node values to their heights in a binary tree

My task is to change the values of nodes to their heights in a binary tree. By the condition of the task, you need to change all the values in 1 pass of the tree, but you can violate this condition using additional data structures. I have a code, but it does not work correctly. This is the original tree, here is what I want to get, and this is the result of the program written below

JavaScript

Advertisement

Answer

If the TreeNode is

JavaScript

The recursive solution. Basically you need to have knowledge of the right subtree while processing the left subtree and vice-versa. The resulting value of the node depends transitively on the lowest leaf. That means you need to scan whole tree to find it (n operations) and only then you can assign values to the nodes.

So it depends how strong is your requirement of “single-pass” (single iteration over tree and nothing more? or making appropriate adjustment at the end so it’ll be 2*n ~= O(n)).

JavaScript

Prints:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement