后继节点和前驱节点

后继节点

后继节点:就是中序遍历排序中相对的后一个
每次找后继节点都是先找当前节点的右子树中的最左节点
如果没有右子树,则找当前节点的父节点,并且当前节点是父节点的左子树的节点。
红圈代表的是当前节点,箭头代表的后继节点,也就是中序遍历中相对当前节点的下一个。
在这里插入图片描述

public static class Node{
		public int value;
		public Node left;
		public Node right;
		public Node parent;
		public Node(int value) {
			this.value=value;
		}

	}
public static Node findPostNode(Node node) {
		if(node==null)
			return  null;
		Node tmp=null;
		if(node.right!=null)
		{
				tmp=node.right;
				while(tmp.left!=null) {
					tmp=tmp.left;
				}
				return tmp;
		}
		else
		{
			tmp=node;
			while(tmp.parent!=null&&tmp.parent.left!=tmp) {
				tmp=tmp.parent;
			}
			return tmp.parent;
			//if(tmp.parent==null)
				//return tmp.parent;
			
			//else {
			//	return tmp.parent;
			//}
			}
				
		}
	}

前驱节点

public static Node findPreNode(Node node) {
		if(node==null)
			return null;
		Node tmp=null;
		if(node.left!=null) {
			tmp=node.left;
			while(tmp.right!=null)
				tmp=tmp.right;
			return tmp;
		}
		else
		{
			tmp=node;
			while(tmp.parent!=null&&tmp.right!=tmp) {
				tmp=tmp.parent;
			}
			return tmp.parent;
		}
	}

猜你喜欢

转载自blog.csdn.net/qq_42403295/article/details/88758816