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
.
最容易想到的是需要额外空间的解法,中序遍历树找到后一个结点,还有一种不需要额外空间的解法,代码很好理解,自己看吧~
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) { TreeNode res=null; while(root!=null){ if(root.val<=p.val){ root=root.right; } else{ res=root; root=root.left; } } return res; }