simple in-order traversal recursive solution in JAVA


  • 0
    O
    public List<List<Integer>> verticalOrder(TreeNode root) {
            List<List<Integer>> ret = new ArrayList<>();
            votDfs(root, ret);
            return ret;
    }
    private int votIdx = -1;
    private void votDfs(TreeNode root, List<List<Integer>> ret) {
            if (root == null) return;
            votIdx--;
            votDfs(root.left, ret);
            votIdx++;
            # set List index for leftmost node to 0
            if (votIdx < 0) votIdx = 0;
            if (ret.size() - 1 < votIdx) {
                List<Integer> l = new ArrayList<>();
                ret.add(l);
            }
            ret.get(votIdx).add(root.val);
            votIdx++;
            votDfs(root.right, ret);
            votIdx--;
    }
    
    

Log in to reply
 

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