[leetcode 285] Inorder Successor in BST---查詢二叉搜尋樹中某個節點在中序遍歷中的後續節點
阿新 • • 發佈:2019-01-24
Question:
Given a binary search tree and a node in it, find the in-order successor of that node in the BST.
Note: If the given node has no in-order successor in the tree, return null
.
題目意思是給定一個二叉搜尋樹和在這個搜尋樹當中的一個節點P,求在中序遍歷中p的後續節點。
可以知道:
1、如果這個節點p有右孩子,那麼p的後續節點為右子樹的的最左值(即最後一個沒有左孩子的節點);
2、如果節點p沒有右孩子,那就在二叉搜尋樹中搜索節點p,並在從上往下的查詢過程中依次更新記錄比p的 val值大的節點。
程式碼如下(參考):
<span style="font-size:14px;">class Solution { public: TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) { if (p -> right) return leftMost(p -> right); TreeNode* suc = NULL; while (root) { if (p -> val < root -> val) { suc = root; root = root -> left; } else if (p -> val > root -> val) root = root -> right; else break; } return suc; } private: TreeNode* leftMost(TreeNode* node) { while (node -> left) node = node -> left; return node; } };</span>