Binary Tree Vertical Order Traversal -> Sequence incorrect should give incorrect answer. Correct Test Cases


  • 0
    S

    /**

    • Definition for a binary tree node.
    • public class TreeNode {
    • int val;
      
    • TreeNode left;
      
    • TreeNode right;
      
    • TreeNode(int x) { val = x; }
      
    • }
      */
      class Solution {
      int min = 0;
      int max = 0;
    public void setHorizontalBar(TreeNode root , int pos){
        if(root == null)
            return;
        
        if(pos< min)
            min = pos;
        if(pos > max)
            max = pos;
        setHorizontalBar(root.left, pos-1);
        setHorizontalBar(root.right, pos+1);
    }
    
    
    public void populateLevels(List<List<Integer>> result, TreeNode root, int pos){
        if(root == null)
            return;
        result.get(pos-min).add(root.val);
        populateLevels(result, root.left , pos - 1);
        populateLevels(result, root.right , pos + 1);
    }
    
    public List<List<Integer>> verticalOrder(TreeNode root) {
        if(root == null){
            return null;
        }
        setHorizontalBar(root, 0);
         
        int levels = max-min+1;
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        for(int i=0;i<levels;i++){
            result.add(new ArrayList<Integer>());
        }
        
        populateLevels(result, root , 0);
        
        return result;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.