给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
/* public class TreeLinkNode { int val; TreeLinkNode left = null; TreeLinkNode right = null; TreeLinkNode next = null; TreeLinkNode(int val) { this.val = val; } } */ public class Solution { public TreeLinkNode GetNext(TreeLinkNode pNode) { } }
写一个函数返回中序下的下一个结点。
思路:
//当前结点为根结点时:
//1)若根结点无右子树,返回NULL
/2)若根结点有右子树,返回右子树中最左端的结点
//当前结点为左叶子结点:
//直接返回其父结点
//当前结点为右叶子结点
//1)若其祖父结点存在且其父结点是其祖父结点的左结点,返回其祖父结点
//2)否则,返回NULL
//当前结点为非叶子结点
//1)若无右子树,返回其父结点
//2)若有右子树,返回其右子树中最左端的结点
public class Solution { public TreeLinkNode GetNext(TreeLinkNode pNode) { if(pNode==null) return null; TreeLinkNode temp; //当前结点为根结点 if(pNode.next==null){ //无右子树 if(pNode.right==null){ return null; }else { temp=pNode.right; while(temp.left!=null){ temp=temp.left; } return temp; } } //当前结点为左叶子结点 if((pNode.left==null&&pNode.right==null)&&(pNode.next.left==pNode)){ //无右子树 if(pNode.right==null){ return pNode.next; }else{ //找到右子树的最左子叶子结点 temp=pNode.right; while(temp.left!=null){ temp=temp.left; } return temp; } } //当前结点为右叶子结点 if((pNode.left==null&&pNode.right==null)&&(pNode.next.right==pNode)){ //当祖父结点是否存在 if(pNode.next.next!=null&&pNode.next.next.left==pNode.next){ return pNode.next.next; }else{ return null; } } if(pNode.right!=null){ temp=pNode.right; while(temp.left!=null){ temp=temp.left; } return temp; }else{ return pNode.next; } } }