/**
* 后继节点就是 中序遍历的下一个节点
* @author 小纸人
*
*/
public class FindSuccessorNode {
static class Node{
int value;
Node left;
Node right;
Node parent;
public Node(int data) {
value = data;
}
}
public static Node getSuccessorNode(Node node) {
if(node == null)
return null;
//
if(node.right != null) {
//后继节点为右子树最左的节点
return getLeftNode(node.right);
}else {
//后继节点为(自己看吧)
Node parent = node.parent;
while(parent != null && parent.left != node) {
node = parent;
parent = node.parent;
}
return parent;
}
}
public static Node getLeftNode(Node node) {
while(node.left != null) {
node = node.left;
}
return node;
}
//for test
public static void main(String[] args) {
Node head = new Node(5);
head.parent = null;
head.left = new Node(3);
head.left.parent = head;
head.right = new Node(8);
head.right.parent = head;
Node node = getSuccessorNode(head.right);
if(node == null)
System.out.println("null");
else
System.out.println(node);
}
}
寻找一颗二叉树的后继节点
最新推荐文章于 2023-08-05 17:20:41 发布