Num8- 二叉树的下一个节点
一、题目描述
给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
二、分析题目
- 中序遍历的顺序 左根右
- 节点中有指向父亲节点的指针
- 特殊值部分:输入为空的情况
三、方法
1.分类讨论
由中序的特点可知,
1. 若当前节点有右子树 , 那么下一个节点就是当前节点的 右孩子
2. 若当前节点无右子树,分三种情况
- 当前节点无父亲节点(也就是当前节点为根节点)–返回null
- 当前节点是其父亲节点的左孩子,则返回当前节点的父亲节点
- 当前节点是其父亲节点的右孩子,那么我们就得找到第一个将其父亲节点作为左孩子的祖先节点。 例如,再上图中,节点 i 就得找到 节点 a
代码如下:
// 二叉树的下一个顶点
public static BiTreeNode NextNode(BiTreeNode root, BiTreeNode node){
if(root==null||node==null)
return null;
//1.节点为根节点的情况
if (node.father==null){
System.out.println("为根节点");
if (node.rChild==null)
return null;
System.out.println("且有右孩子");
BiTreeNode p = node.rChild;
if (p.lChild==null)
return p;
while (p.lChild!=null){
p = p.lChild;
}
return p;
}
BiTreeNode father = node.father;
//2.无右孩子情况
if (node.rChild==null){
//node为左孩子
if(father.lChild==node)
return father;
//node为右孩子,且无右孩子
else {
//父亲节点为根节点
if(father.father == null){
return null;
}else {
//父亲节点是左孩子
if (father.father.lChild == father)
return father.father;
else {
//找到祖先节点
BiTreeNode cur = node;
while (father != null && father.rChild == cur){
cur = father;
father = father.father;
}
return father;
}
}
}
}
//3.只要有右孩子
return node.rChild;
}
总结
在该算法的过程中,得将各种情况都考虑到位,特别是 当前节点无右孩子,且为其父亲节点的右孩子时,我们得找到第一个将其父亲节点作为左孩子的祖先节点。