Problem:given a tree, color nodes black as many as possible without coloring, adjacent nodes
Idea: If the root node R is marked black, its immediate child node cannot be marked black, and if R is not marked, its child nodes can be marked black, resulting in a state transition equation:
Find (r) = Max (Black (R), White (R))
Black (R) is the number of nodes in the tree with the r root node that can be marked as dark when node R is marked as Black
White (R) is the number of nodes in the tree with r root that can be marked as black when node R is not marked as black
The
White (R) = Find (R.left) + Find (r.right)
When r is not marked as black, the left and right child nodes continue to look for
Black (r) = 1 + whilte (r.left) + White (r.right)
When R is marked black, it contributes 1 to the total number of black nodes, and then its left and right child nodes must be non-black nodes.
1 Packagecom.self;2 3 Public classDp_03_tree {4 5 Public Static voidMain (string[] args) {6 7Node node4 =NewNode (4);8Node Node3 =NewNode (3);9Node NODE5 =NewNode (5);TenNode Node2 =NewNode (2); OneNode Node1 =NewNode (1); A -Node4.left =Node3; -Node4.right =Node5; theNode3.left =Node2; -Node3.right =Node1; - -Dp_03_tree app =NewDp_03_tree (); + intMaxblack =App.find (NODE4); - System.out.println (maxblack); + } A at intFind (Node node) { - if(NULL= = node)return0; - if(NULL= = Node.left &&NULL= = Node.right)return1; - returnMath.max (Findfromwhite (node), Findfromblack (node)); - } - in //Current node was white - intFindfromwhite (node node) { to if(NULL= = node)return0; + returnFind (Node.left) +find (node.right); - } the * //Current node is black $ intFindfromblack (node node) {Panax Notoginseng if(NULL= = node)return0; - //Current node was black, then its children does not count, but itself counts the return1 + findfromwhite (node.left) +Findfromwhite (node.right); + } A } the + classnode{ - intv; $ Node left; $ Node right; -Node (intv) { - This. v =v; the } -}
Finding the most black nodes in a binary tree