值的性质:左节点 <=
根节点 <=
右节点
设计一个算法,找出二叉搜索树中指定节点的“下一个”节点(也即中序后继)。
如果指定节点没有对应的“下一个”节点,则返回null。
示例:
输入: root = [2,1,3], p = 1
2
/ \
1 3
输出: 2
var inorderSuccessor = function(root, p) {
let r = null
while (root) {
if (root.val > p.val) {
r = root
root = root.left
} else {
root = root.right
}
}
return r
};
func inorderSuccessor(root *TreeNode, p *TreeNode) *TreeNode {
var r *TreeNode
for root != nil {
if root.Val > p.Val {
r = root
root = root.Left
} else {
root = root.Right
}
}
return r
}
class Solution {
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
TreeNode r = null;
while (root != null) {
if (root.val > p.val) {
r = root;
root = root.left;
} else {
root = root.right;
}
}
return r;
}
}
class Solution:
def inorderSuccessor(self, root: TreeNode, p: TreeNode) -> TreeNode:
r = None
while root:
if root.val > p.val:
r = root
root = root.left
else:
root = root.right
return r
def inorder_successor(root, p)
r = nil
while root do
if root.val > p.val
r = root
root = root.left
else
root = root.right
end
end
return r
end
struct TreeNode* inorderSuccessor(struct TreeNode* root, struct TreeNode* p){
struct TreeNode *r = NULL;
while (root != NULL) {
if (root->val > p->val) {
r = root;
root = root->left;
} else {
root = root->right;
}
}
return r;
}
class Solution {
public:
TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
TreeNode* r = nullptr;
while (root != nullptr) {
if (root->val > p->val) {
r = root;
root = root->left;
} else {
root = root->right;
}
}
return r;
}
};
public class Solution {
public TreeNode InorderSuccessor(TreeNode root, TreeNode p) {
TreeNode r = null;
while (root != null) {
if (root.val > p.val) {
r = root;
root = root.left;
} else {
root = root.right;
}
}
return r;
}
}