I want a better algorithm,i think my code is a little weird,how can i improve it?


  • 0
    P

    this is my code:

      public ArrayList<Integer> inorderTraversal(TreeNode root) {
    	  ArrayList<Integer> inorder=new ArrayList<Integer>();
    	  if(root==null)return inorder;
    	  Stack<TreeNode> st=new Stack<TreeNode>();
    	  st.push(root);
    	  while(root.left!=null){
    		  st.push(root.left);
    		  root=root.left;
    	  }
    	  while(root!=null&&!st.empty()){
    		  root=st.pop();
    		  inorder.add(root.val);
    		  if(root.right!=null){
    			  st.push(root.right);
    			  while(root.right.left!=null){
    				  st.push(root.right.left);
    				  root.right=root.right.left;
    			  }
    		  }
    	  }
    	  return inorder;
        }
    

    any suggestion will be appreciated


  • 0
    S

    You're changing the tree with "root.right=root.right.left". It's better not to do that.


Log in to reply
 

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