Easy java solution using inorder traversal


  • 0
    D

    /**

    • Definition for a binary tree node.

    • public class TreeNode {

    • int val;
      
    • TreeNode left;
      
    • TreeNode right;
      
    • TreeNode(int x) { val = x; }
      
    • }
      */
      public class Solution {
      public int kthSmallest(TreeNode root, int k) {

       //variable to store the answer
       List<Integer> result=new ArrayList<Integer>();
       
       //call an inorder traversal function
       inorder(root,result);
       
       //return the kth index as the answer
       return result.get(k-1);
      
    }
    
    public void inorder(TreeNode root, List<Integer> result)
    {
        //Base case: if root is null, return the list
        if(root==null)
            return ;
            
        //traverse the tree in an inorder fashion
        inorder(root.left,result);
        result.add(root.val);
        inorder(root.right,result);
        
    }
    

    }


  • 0
    I

    Definitely easy to understand, but it doesn't make use of the hints at all.


Log in to reply
 

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