C# Traversal BST stop at the nth


  • 0
    Y

    /**

    • Definition for a binary tree node.
    • public class TreeNode {
    • public int val;
      
    • public TreeNode left;
      
    • public TreeNode right;
      
    • public TreeNode(int x) { val = x; }
      
    • }
      */
    public class Solution {
        public int KthSmallest(TreeNode root, int k) {
        
        if(root==null)
        {
            return 0;
        }
        
        var result=new List<int>();
    	travelsList(root, k, result);
        
        return result[result.Count-1];
        
    }
    
    
     public static void travelsList(TreeNode root, int k, List<int> result)
    {        
    	
        
        if(root.left != null)
        {
            travelsList(root.left, k, result);
        }
    	
    	if(result.Count == k)
        {
            return;
        }
        
        result.Add(root.val);        
       
        
        if(root.right != null)
        {
            travelsList(root.right, k, result);
        }
        
        return;
      }
      
    }

Log in to reply
 

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