/* 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) { //中序递归 int count = 0; if(count > k || pRoot == NULL) return NULL; TreeNode* p = pRoot; stack<TreeNode*> LDRStack; TreeNode* kthNode; while(p != NULL || !LDRStack.empty()){ while(p != NULL){ LDRStack.push(p); p = p->left; } TreeNode* node = LDRStack.top(); LDRStack.pop(); count++; if(count == k){ kthNode = node; } p = node->right; } return kthNode; } };
时间: 2024-11-06 12:55:56