之前寒假做了这道题用队列,队列存中序遍历的结果,然后输出第K个,这样需要浪费空间,今天重新做了一次,空间复杂度为0。
/*
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, unsigned int k)
{
if(pRoot == NULL)
return NULL;
if(k < 1)
return NULL;
TreeNode * x = NULL;
int num = 0;
dfs(pRoot, x, k, num);
if(x == NULL)
return NULL;
else
return x;
}
void dfs(TreeNode * head, TreeNode * & x, int k, int & num)
{
if(num > k)
return ;
if(head -> left != NULL)
{
dfs(head -> left, x, k, num);
}
num++;
if(num == k)
{
x = head;
return ;
}
if(head -> right != NULL)
dfs(head -> right, x, k, num);
}
};