Java binary tree inorder traversal solution


  • 1
    V

    /**

    • Definition for binary tree
    • public class TreeNode {
    • int val;
      
    • TreeNode left;
      
    • TreeNode right;
      
    • TreeNode(int x) { val = x; }
      
    • }
      */

    public class Solution {

    public List<Integer> inorderTraversal(TreeNode root) {
         List<Integer> ret = new ArrayList<Integer>();
         if (root == null) {
            return ret;
         }
         
         Stack<TreeNode> s = new Stack<TreeNode>();
         TreeNode cur = root;
         
         while (true) {
             while (cur != null) {
                 s.push(cur);
                cur = cur.left;
             }
             
             if (s.isEmpty()) {
                 break;
             }
             
             cur = s.pop();
             ret.add(cur.val);
             
             cur = cur.right;
         }
         
         return ret;
     }
    

    }


  • 3
    J
    /**
     * Definition for binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public List<Integer> inorderTraversal(TreeNode root) {
            List<Integer> result = new ArrayList<Integer>();
            Stack<TreeNode> nodeStack = new Stack<TreeNode>();
            
            while (root != null || !nodeStack.isEmpty()) {
                while (root != null) {
                    nodeStack.push(root);
                    root = root.left;
                }
                
                root = nodeStack.pop();
                result.add(root.val);
                root = root.right;
            }
            
            return result;
        }
    }

Log in to reply
 

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