About binary trees, I understand the difference between size and height: size is the number of nodes while height of a tree is the max number of edges from the root to the furthest leaf.
However, when dealing with problems involving height, my mind is often twisted and can't think straight.
For the following two problems, they are very similar except one with constraints on size while the other one with height.
For example, let's first have the one involving size.
In a completely balanced binary tree, the following property holds for every node: The number of nodes in its left subtree and the number of nodes in its right subtree are almost equal, which means their difference is not greater than one.
Write a function to construct all possible completely balanced binary trees for a given number of nodes - n. The function should generate all solutions via backtracking. Put the letter 'x' as information into all nodes of the tree.
This problem is to generate all possible completely balanced binary tress as long as the property is held.
I think size is simple. What I can do is like this:
- Using recursion
- If n mod 2 = 1, then generate all such trees with
n=n/2, then merge every pair of those trees with a new root. - If n mod 2 = 0, then generate one set of trees with
n/2and another set of trees withn/2-. then merge every pair (one from a set) with a new root, also don't forget to exchange the elements inside every pair. - If n = 0 then return a set with only one Leaf
- If n = 1 then return a set with only one singleton internal node with two Leaves.
When the size in the problem is changed to height, I don't really know how to cleverly think any more.
In a height-balanced binary tree, the following property holds for every node: The height of its left subtree and the height of its right subtree are almost equal, which means their difference is not greater than one.
Write a function to construct all possible height-balanced binary trees for a given number of nodes - n. The function should generate all solutions via backtracking. Put the letter 'x' as information into all nodes of the tree.
I think if involving height, things get quite arbitrary.
Is the solution for the 2nd problem is the same as the 1st problem?
How really should I train myself to handle the height thing? Where is the trick?