二叉树-后继节点
作者:互联网
在二叉树中找到一个节点的后继节点
二叉树节点多了个属性 parent
public static class NewNode {
public int value;
public NewNode left;
public NewNode right;
public NewNode parent;
public NewNode(int val) {
value = val;
}
}
头节点的parent指向null
在二叉树的中序遍历中,node 的下一个节点就是node的后继节点
第一种,中序遍历,保存在数组中。太low
第二种,利用parent指针, 分俩大类情况
1)当前节点没有右子树,然后直到 某个节点是父节点的左孩子。那么它的后继节点就是 当前父节点
2)当前节点有右子树,右子树最左的node就是他的后继节点。
public static NewNode findNextNode(NewNode newNode) {
if (newNode == null) {
return null;
}
if (newNode.right != null) {
// 有右子树的情况, 右子树最左的节点,
return findLeftNewNode(newNode.right);
} else {
// 没有右孩子
// 往上 找到直到 某个节点是自己父亲的左孩子
while (newNode.parent != null) {
if (newNode.parent.left == newNode) {
return newNode.parent;
}
newNode = newNode.parent;
}
}
return null;
}
public static NewNode findLeftNewNode(NewNode newNode) {
while (newNode.left != null) {
newNode = newNode.left;
}
return newNode;
}
标签:null,parent,public,二叉树,NewNode,newNode,后继,节点 来源: https://www.cnblogs.com/clllll/p/16245001.html