Java 1ms solution


  • 2
    L
    public class Solution {
        public List<List<Integer>> findLeaves(TreeNode root) {
            List<List<Integer>> results=new ArrayList<List<Integer>>();
            if(root==null) return results;
            
            while(root!=null){
                List<Integer>list=new ArrayList<Integer>();
                if(dfs(list,root)) root=null;
                results.add(list);
            }
            
            return results;
        }
        
        private boolean dfs(List<Integer>list,TreeNode node){
            
            if(node.right==null && node.left==null) {
              list.add(node.val);
                return true;
            }
            
              if(node.left!=null)
            {
                if(dfs(list,node.left)) node.left=null;
                
            }
            if(node.right!=null){
                if(dfs(list, node.right)) node.right=null;
                
            };
            
            return false;
        }
    }
    

Log in to reply
 

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