Recursive solution using JAVA


  • 1
    J

    public class Solution {

    public List<Integer> preorderTraversal(TreeNode root) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        traverse(root, list);
        return list;
    }
    
    public void traverse(TreeNode node, ArrayList<Integer> list) {
        if(node == null) {
            return;
        }
        
        list.add(node.val);
        traverse(node.left, list);
        traverse(node.right, list);
        
    }
    

    }


  • 0
    J
    public class Solution {
    	List<Integer> result = new ArrayList<Integer>();
    
    	public List<Integer> preorderTraversal(TreeNode root) {
    		if (null == root) {
    			return result;
    		}
    		result.add(root.val);
    		preorderTraversal(root.left);
    		preorderTraversal(root.right);
    		return result;
    	}
    }

Log in to reply
 

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