Simple post order traversal JAVA


  • 0
    J
    public class Solution {
        public List<List<Integer>> findLeaves(TreeNode root) {
            List<List<Integer>> res = new ArrayList<>();
            dfs(root, res);
            return res;
        }
        
        private int dfs(TreeNode x, List<List<Integer>> res) {
            if (x == null) return -1;
            int left = dfs(x.left, res);
            int right = dfs(x.right, res);
            int d = Math.max(left, right) + 1;
            if (res.size() == d) res.add(new ArrayList<>());
            res.get(d).add(x.val);
            return d;
        }
    }

Log in to reply
 

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