二叉搜索树_前趋结点_后继结点
左子树上的所有节点 一定比根节点 小
右子树上的所有节点 一定比根节点 大
中序遍历 就是从小大到的顺序
最大关键结点
maxElemNode: 获取二叉树最大的结点 一直向右循环寻找就是二叉树的最大结点
public TreeNode maxElemNode(TreeNode node) throws Exception {
if (node == null) {
throw new Exception("树为空!");
}
TreeNode pNode = node;
while (pNode.rightChild != null) {
pNode = pNode.rightChild;
}
return pNode;
}
最小关键结点
minElemNode:获取二叉树最小结点 一直向左循环就是二叉树的最小结点
public TreeNode minElemNode(TreeNode node) throws Exception {
if (node == null) {
throw new Exception("树为空!");
}
TreeNode pNode = node;
while (pNode.leftChild != null) {
pNode = pNode.leftChild;
}
return pNode;
}
前趋节点
中序遍历为 左中右 即左面树最小 ,所以如果当前结点有左孩子,那么这个左孩子就是他的前趋节点
如果当前结点没有左孩子 如果当前值最小 那么他的前趋结点为null
如果当前值不是最小 那么他的前趋节点为 父节点 并且他不是这个父节点的左子
左 中(父结点) 右(当前节点)
比如下面这个数组 6 1 9 8 2 3 4 10
中序遍历的顺序为 1 2 3 4 6 8 9 10
如果求9的前趋结点很简单 9有左孩子为8
如果求1的前趋结点,1没有左子树 看1的父结点为6 而1又是父结点的左孩子 ,所以父结点6不是他的前趋
再看6的父结点为NULL 所以1没有前趋结点 或者说1的前趋为NULL
如果求8的前趋结点, 8没有左子树,则看他的父结点为9 ,而8又是父节点的左孩子 ,所以9一定不是8的前趋
再看9的父节点为6 而9又是6的右孩子 所以9的父节点6 就是8的前趋
用程序表现这段描述就是
public TreeNode precessor1(TreeNode node) throws Exception {
if(node ==null) {
return null;
}
if(node.leftChild!=null) {//有左孩子
return maxElemNode(node.leftChild);
}else {//没有左孩子
TreeNode parent = node.parent;
while(true) {
if(parent==null) {
break;
}
if(node==parent.leftChild) {//当前结点是父结点的左孩子 此时父结点大
//改变node parent
node = parent;
parent = parent.parent;
}else {//当前结点是父节点右孩子 退出 那么父结点一定是前趋
break;
}
}
return parent;
}
}
----------------------------------
后继结点
public TreeNode successor1(TreeNode node) throws Exception {
if (node == null) {
return null;
}
// 若该结点的右子树不为空,则其后继结点就是右子树中的最小关键字结点
if (node.rightChild != null) {
return minElemNode(node.rightChild);
}
// 若该结点右子树为空
TreeNode parentNode = node.parent;
while (true) {
if(parentNode==null) {
break;
}
if(node==parentNode.rightChild) {//当前节点 是父节点的右子树 那么父结点为后继节点
break;
}else {//否则
node = parentNode;
parentNode = parentNode.parent;
}
}
return parentNode;
}