Thursday, May 29, 2014

Sink Zeros in Binary Tree


 Swap zero value of a node with non-zero value of one of its descendants so that no node with value zero could be parent of node with non-zero.

Solution: 

We use a postorder traversal of the tree where instead of sinking we rise the leafs, we keep the nodes that we are sure that have not a zero ancestor.

public  void sink0(TreeNode root)
 {
  HashSet<TreeNode> finished = new HashSet<TreeNode>();
  sink0(root, new HashMap<TreeNode,TreeNode>(), finished, false);
 }
 
 public void sink0(TreeNode root, HashMap<TreeNode, TreeNode> parentMap, HashSet<TreeNode> finished, boolean zerosOver)
 {
  if(root.val==0)
   zerosOver = true;
  if(!zerosOver)
   finished.add(root);
  
  if(root.left != null)
  {
   parentMap.put(root.left, root);
   sink0(root.left, parentMap, finished, zerosOver);
  }
  if(root.right != null)
  {
   parentMap.put(root.right, root);
   sink0(root.right, parentMap, finished, zerosOver);
  }
  if(root.val!=0 && !finished.contains(root))
  {
   TreeNode temp = root;
   ArrayDeque<TreeNode> nonZeroNodes = new ArrayDeque<TreeNode>();
   ArrayDeque<TreeNode>nodes = new ArrayDeque<TreeNode>();
   while(temp!=null && !finished.contains(temp))
   {
    nodes.push(temp);
    if(temp.val!=0)
     nonZeroNodes.push(temp);
    temp = parentMap.get(temp);
   }
   
   while(!nonZeroNodes.isEmpty())
   {
    TreeNode tempNode = nonZeroNodes.pop();
    TreeNode toModify = nodes.pop();
    toModify.val = tempNode.val;
    finished.add(toModify);
   }
   while(!nodes.isEmpty())
   {
    TreeNode toModify = nodes.pop();
    toModify.val=0;
   }
  }
 }

No comments :

Post a Comment