【题目】现在有一种新的二叉树节点类型如下:
代码语言:javascript复制 public class Node {
public int value;
public Node left;
public Node right;
public Node parent;
public Node(int data) {
this.value = data;
}
}
该结构比普通二叉树节点结构多了一个指向父节点的parent指针。 假设有一棵该Node类型的节点组成的二叉树,树中每个节点的parent指针 都正确地指向自己的父节点,头节点的parent指向null。 只给一个在二叉树中的某个节点 node,请实现返回node的后继节点的函数。 在二叉树的中序遍历的序列中, node的下一个节点叫作node的后继节点。node的上一个节点叫作node的钱去节点.,如某树遍历结果是5 1 4 3 8 7 9,那么1的后继结点就是4,1的前驱结点是5
第一种方法 : 很简单,中序遍历整个树,把结果存起来,查一下要找的数后面的值即可.但是这种时间复杂度比较高,每次需要遍历整个树
第二种方法 :其实一个结点的后继结点有这样一个规律
- 如果当前结点有右子树,则其后继结点是右子树的最左结点
- 如果当前结点没有右子树,则从父结点开始向上找,一直到当前结点是其父结点的左孩子时候停,那么当前结点的父结点就是其后继结点.
代码
代码语言:javascript复制package com.algorithm.practice.tree;
public class FindPosNodeFromTree {
public static class Node {
public int value;
public Node left;
public Node right;
public Node parent;
public Node(int data) {
this.value = data;
}
}
public static Node getSuccessorNode(Node node) {
if (node==null){
return null;
}
if (node.right!=null){
return leftest(node.right);
}else {
Node parent=node.parent;
while (parent!=null&&node!=parent.left){
node=node.parent;
parent=node.parent;
}
return parent;
}
}
private static Node leftest(Node curr) {
while (curr.left!=null){
curr=curr.left;
}
return curr;
}
public static void main(String[] args) {
Node head = new Node(6);
head.parent = null;
head.left = new Node(3);
head.left.parent = head;
head.left.left = new Node(1);
head.left.left.parent = head.left;
head.left.left.right = new Node(2);
head.left.left.right.parent = head.left.left;
head.left.right = new Node(4);
head.left.right.parent = head.left;
head.left.right.right = new Node(5);
head.left.right.right.parent = head.left.right;
head.right = new Node(9);
head.right.parent = head;
head.right.left = new Node(8);
head.right.left.parent = head.right;
head.right.left.left = new Node(7);
head.right.left.left.parent = head.right.left;
head.right.right = new Node(10);
head.right.right.parent = head.right;
Node test = head.left.left;
System.out.println(test.value " next: " getSuccessorNode(test).value);
test = head.left.left.right;
System.out.println(test.value " next: " getSuccessorNode(test).value);
test = head.left;
System.out.println(test.value " next: " getSuccessorNode(test).value);
test = head.left.right;
System.out.println(test.value " next: " getSuccessorNode(test).value);
test = head.left.right.right;
System.out.println(test.value " next: " getSuccessorNode(test).value);
test = head;
System.out.println(test.value " next: " getSuccessorNode(test).value);
test = head.right.left.left;
System.out.println(test.value " next: " getSuccessorNode(test).value);
test = head.right.left;
System.out.println(test.value " next: " getSuccessorNode(test).value);
test = head.right;
System.out.println(test.value " next: " getSuccessorNode(test).value);
test = head.right.right; // 10's next is null
System.out.println(test.value " next: " getSuccessorNode(test));
}
}
同理 如果找其前驱结点
- 如果当前该结点有左子树则其前驱结点是左子树的最右结点
- 如果当前结点没有左子树,那么向上查找,如果当前结点是其父的右孩子,那么其父是要找结点的前驱结点