graph - Partition a Binary Tree into two tree such that the difference of their diameter is less than a specific value K -


given binary tree. have remove edge , partition two trees such difference of diameter of 2 new trees less specified value k.

i have naive solution picks each edge , checks condition if removing edge can obtain solution or not (we can using 2 dfs/bfs , calculate diameter). makes solution o(n^2).

can suggest me better approach mine?

i think can use dynamic programing this, unable visualize it.

it enough each node calculate height of tree below it. leaf node 0, , other nodes max(height of children) + 1. done tree post-order traversing.

diameter of binary tree height of left child + height of right child + 1. general trees (sum of 2 max heights) + 1.

idea of algorithm start root , 'climb down' higher child, while checking difference between diameter of child's subtree , rest of tree. can done calculated heights.

update

 root  / \ l   r 

in tree, diameter pass through root node, or in 1 of subtrees. that:

root.diameter = max(l.height + r.height + 2, l.diameter, r.diameter).

if cut edge, e.g. edge between n , n.l:

  root   /  \  ...  ...   |   n  / \ l   r 

l subtree has diameter upper formula. rest of tree has diameter

max(r.height + length(r, root) + root.height, root.r.diameter, r.diameter).

terms r.height , r.diameter depends on edge want check. terms root.height , root.r.diameter static while checking edges in root.l subtree (and vice verse). term length(r, root) depends on edge depth root, easy track.

with possible create method recursively checks cuts on 1 subtree edges.


Comments

Popular posts from this blog

How to understand 2 main() functions after using uftrace to profile the C++ program? -

c# - Update a combobox from a presenter (MVP) -

How to put a lock and transaction on table using spring 4 or above using jdbcTemplate and annotations like @Transactional? -