第62题 二叉搜索树的第k个结点
题目描述
给定一棵二叉搜索树,请找出其中的第k小的TreeNode结点。
该题可以用栈模拟中序遍历的递归,先将左子树入栈,到底出栈得到根节点,再转向右子树,以此循环,得到中序遍历 详见:栈模拟遍历
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
int m;
TreeNode* ans = nullptr;
void dfs(TreeNode* root){
if(!root || m < 1) return;
dfs(root->left);
if(m==1) ans = root;
--m;
dfs(root->right);
}
TreeNode* KthNode(TreeNode* pRoot, int k) {
m = k;
dfs(pRoot);
return ans;
}
};
栈实现中序遍历:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def kthLargest(self, root: TreeNode, k: int) -> int:
t = 0
st = []
while st or root:
while root:
st.append(root)
root = root.right
if st:
node =st.pop()
t += 1
if t == k:
return node.val
root = node.left
return None
思路:
递归-左子树-判断m是否为1-递减m-右子树
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
TreeNode* KthNode(TreeNode* pRoot, int k) {
if(!pRoot) return nullptr;
stack<TreeNode*> res;
while(!res.empty() || pRoot){
while(pRoot){
res.push(pRoot);
pRoot = pRoot->left;
}
TreeNode* node = res.top();
res.pop();
if((--k)==0) return node;
pRoot = node->right;
}
return nullptr;
}
};```