?LeetCode刷題實戰(zhàn)285:二叉搜索樹中的順序后繼
Given a binary search tree and a node in it, find the in-order successor of that node in the BST.
The successor of a node p is the node with the smallest key greater than p.val.
示例
輸入: root = [2,1,3], p = 1
輸出: 2
解析: 這里 1 的順序后繼是 2。
請注意 p 和返回值都應(yīng)是 TreeNode 類型。
解題
class Solution {
public:
TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
stack<TreeNode*> s;
bool b = false;
TreeNode *t = root;
while (t || !s.empty()) {
while (t) {
s.push(t);
t = t->left;
}
t = s.top(); s.pop();
if (b) return t;
if (t == p) b = true;
t = t->right;
}
return NULL;
}
};
評論
圖片
表情
