题目描述
给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
思路:
二叉搜索树按照中序遍历的顺序打印出来正好就是排序好的顺序。
所以,按照中序遍历顺序找到第k个结点就是结果。
python
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回对应节点TreeNode
def KthNode(self, pRoot, k):
# write code here
#第三个节点是4
#前序遍历5324768
#中序遍历2345678
#后序遍历2436875
#所以是中序遍历,左根右
global result
result=[]
self.midnode(pRoot)
if k<=0 or len(result)<k:
return None
else:
return result[k-1]
def midnode(self,root):
if not root:
return None
self.midnode(root.left)
result.append(root)
self.midnode(root.right)
c++
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
TreeNode* KthNodeCore(TreeNode* pRoot, int& k)
{
TreeNode* target = NULL;
if(pRoot->left != NULL)
target = KthNodeCore(pRoot->left, k);
if(target == NULL)
{
if(k == 1)
target = pRoot;
k--;
}
if(target == NULL && pRoot->right != NULL)
target = KthNodeCore(pRoot->right, k);
return target;
}
TreeNode* KthNode(TreeNode* pRoot, int k)
{
if(pRoot == NULL || k == 0)
return NULL;
return KthNodeCore(pRoot, k);
}
};