Simple tree traversal Java O(N)


  • 0
    I
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public List<List<Integer>> findLeaves(TreeNode root) {
            List<List<Integer>> res = new ArrayList<List<Integer>>();
            if(null == root) {
                return res;
            }
            
            traverse(res, root);
            
            return res;
        }
        
        int traverse(List<List<Integer>> res, TreeNode root) {
            if(null == root) {
                return 0;
            }
            
            int pos = Math.max(traverse(res, root.left), traverse(res, root.right));
            if(pos == res.size()) {
                res.add(new ArrayList<Integer>());
            }
            
            res.get(pos).add(root.val);
            return pos + 1;
        }
    }
    

Log in to reply
 

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