题解
- 中序遍历记格数即可
AC-Code
/*
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 == NULL) return NULL;
int num = 0;
stack<TreeNode*> st;
TreeNode * p = pRoot;
while(p != NULL || !st.empty()) {
while(p != NULL) {
st.push(p);
p = p->left;
}
if(!st.empty()) {
p = st.top();
st.pop();
++num;
if(num == k) return p;
p = p->right;
}
}
return NULL;
}
};