2 ms simple Inorder traversal Java


  • 0
    J

    Just do simple inorder traversal while keeping track of count.

    public class Solution {
    static TreeNode kthNode = null; static int count = 0; 
    public int kthSmallest(TreeNode root, int k) {
        kthNode = null;
        count = 0;
        inOrderDriver(root, k);
        return kthNode.val;
       } 
    
    private void inOrderDriver(TreeNode node, int k) {
        if (node == null) return;
        inOrderDriver(node.left, k);
        count++;
        if (count == k) {
          kthNode = node;
          return;
        }
        inOrderDriver(node.right, k);
    }
    

    }


Log in to reply
 

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