C++ 栈的中序遍历
二叉搜索树的第k个结点
http://www.nowcoder.com/questionTerminal/ef068f602dde4d28aab2b210e859150a
C++ 栈利用 时间复杂度最大O(N)
从根节点开始入栈,出栈方向就是中序遍历。
/* 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 == nullptr || k == 0) return nullptr; stack<TreeNode*> S; int count = 0; TreeNode* res = pRoot; while(res != nullptr || !S.empty()) { if(res != nullptr) { S.push(res); res = res->left; } else { res = S.top(); S.pop(); if(++count == k) return res; res = res->right; } } return nullptr; } };