Java iterative solution with o(1)


  • 0
    N
    /**
     * 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<Integer> preorderTraversal(TreeNode root) {
            List<Integer> list = new ArrayList<Integer>();
            if(root == null)
                return null;
            TreeNode tmpRoot = root;
            while(tmpRoot != null){
                TreeNode tmp = tmpRoot.left;
                if(tmp != null){
                    while(tmp.right != null && tmp.right != tmpRoot)
                        tmp = tmp.right;
                    if(tmp.right == null){
                        tmp.right = tmpRoot;
                        list.add(tmpRoot.val);
                        tmpRoot = tmpRoot.left;
                    }
                    else{
                        tmpRoot = tmpRoot.right;
                    }
                }
                else{
                    list.add(tmpRoot.val);
                    tmpRoot = tmpRoot.right;
                }
            }
        }
    }

  • 0
    L
     public List<Integer> preorderTraversal(TreeNode root) {
    	        List<Integer> pro =new ArrayList<Integer>();
    	        proTravelsal(root,pro);
    	        return pro;
    	    }
    	 public void  proTravelsal(TreeNode root, List<Integer> por){
    		 if(root!=null){
    			 por.add(root.val);
    		 proTravelsal(root.left,por);
    		 proTravelsal(root.right,por);
    		 }
    	 }

Log in to reply
 

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