54 二叉搜索树的第k小节点

题目

找出二叉搜索树的第k大节点。例如,在下图的树里,第3大节点的值为4,输入该树的根节点,3,则输出4。

Leetcode

C++ 题解

方法一

查找左子树的数量:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int kthSmallest(TreeNode* root, int k) {
        
       int cnt =  Count(root->left);
        
        // 如果左子树刚好是k-1个,那么当前的根节点就是第k小的数字
        if(cnt == k-1)
            return root->val;
        // 左子树的数目大于k-1,说明节点在当前节点左子树的左子树中
        else if(cnt > k -1)
            return kthSmallest(root->left,k);
         // 左子树的数目小于k-1,说明节点在当前节点右子树中
        else
            return kthSmallest(root->right,k - cnt - 1);
        
    }
    
    
    // 统计一颗树的节点个数
    int Count(TreeNode* pRoot)
    {
        if (pRoot == nullptr)
            return 0;
        
        return 1 + Count(pRoot->left) + Count(pRoot->right);
    }
};

方法二

利用栈实现:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
 
class Solution {
 public:
	 int kthSmallest(TreeNode* root, int k) 
     {
		 stack<TreeNode*> s;
		 int res;
		 while ((root || !s.empty()) && k)
         {
			 if (root)
             {
				 s.push(root);
				 root = root->left;
			 }
			 else 
             {
				 root = s.top();
				 s.pop();
				 --k;
				 res = root->val;
				 root = root->right;
			 }
		 }
		 return res;
	 }
 };

python 题解

中序遍历将节点存放在列表中:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def kthSmallest(self, root, k):
        """
        :type root: TreeNode
        :type k: int
        :rtype: int
        """
        if root == None or k <= 0:
            return Node
        
        res = []
            
        def inOrder(root):
            if root == None:
                return []
            inOrder(root.left)
            res.append(root.val)
            inOrder(root.right)
        
        inOrder(root)
        if len(res) < k:
            return None
        else:
            return res[k-1]
posted @ 2019-03-17 11:12  youngliu91  阅读(148)  评论(0编辑  收藏  举报