Recursive inorder travel solution


  • 3
    S
    // recursive inorder travel 
    int kthSmallest(TreeNode* root, int k) {
        int iRet = 0;
        dfs(root, iRet, k);
        return iRet;
    }
    
    void dfs(TreeNode *root, int &iRet, int &k) {
        if (!root || k <= 0) return;
        
        dfs(root->left, iRet, k);
        
        if (k <= 0) return;
        --k;
        if (k == 0) { iRet = root->val; return;}
        
        dfs(root->right, iRet, k);
    }

  • 1
    S

    @shichaotan Maybe your function dfs() can be more concise

    void dfs(TreeNode *root, int &iRet, int &k) {
       if (!root) {
           return;
       }
      dfs(root->left, iRet, k);
      if (!(--k)) {
        iRet = root->val;
        return;
      }
      dfs(root->right, iRet, k);
    }


Log in to reply
 

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