剑指offer:二叉树的下一节点

题意描述

给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。

解题思路

一、暴力解决

分析Node可能在二叉树的所有位置,逐个进行分析。

  1. 若node的右子树不为空,中序遍历的下一节点是右子树的最左节点。
  2. 若node的右子树为空,左子树不为空,中序遍历的下一节点是父节点。
  3. 若node的右子树为空,左子树空,说明是node是叶子节点。
  4. 若node为左叶子,中序遍历的下一节点是父节点。
  5. 若node是右叶子,中序遍历的下一节点是祖父节点。
  6. 特殊情况:①二叉树只有node节点。②斜树。
    public TreeLinkNode GetNext(TreeLinkNode pNode){
	    if(pNode == null) return null;	//pNode为空
        if(pNode.right != null){	//右子树不为空
        	pNode = pNode.right;	
            while(pNode.left != null) 
                pNode = pNode.left;
            return pNode;	//右子树的最左节点
        }else if(pNode.right == null && pNode.left != null){	//右子树为空,左子树不为空
        	return pNode.next;	//返回父节点
        }else{ 	//左右子树都为空,说明是叶子节点
            if(pNode.next == null) return null; //父节点为空,说明只有一个节点
            if(pNode.next.left == pNode) return pNode.next;	//左叶子节点,返回父节点
           	else{	//右叶子节点
            	TreeLinkNode node = pNode.next;
                while(node.next != null) 	
                    node = node.next;	//先找到根节点
                while(node.right != null)
                    node = node.right;
                if(node == pNode){
                	return null;	//斜树的右叶子节点
                }else{
                	return pNode.next.next;	//普通情况,右叶子节点返回祖父节点
                }
            }
        	
        }
    }

二、优化

这里写图片描述

如图所示,可以发现

  1. 又右子树的,下一节点就是右子树的最左节点。(eg:D,B,E,A,C,G)

  2. 没有右子树的,可以分为

    (1)父节点的左孩子(eg:N,I,L),父节点就是下一节点

    (2)父节点的右孩子(eg:H,J,K,M),向上查找父节点,直到当前节点父节点左孩子。如果没有返回尾节点。

	 public TreeLinkNode GetNext(TreeLinkNode pNode){
     	if(pNode == null) return null;	//pNode为空
         if(pNode.right != null){		//右子树不为空
         	pNode = pNode.right;	
             while(pNode.left != null) pNode = pNode.left;
             return pNode;		//返回右子树的最小值
         }
         while(pNode.next != null){		//查找当前节点是父节点的左节点的节点
         	if(pNode.next.left == pNode){
            	return pNode.next;	//返回当前节点的父节点
            }
             pNode = pNode.next;
         }
         return null;	//否则返回null
     }
posted @ 2020-03-14 22:40  灵图  阅读(136)  评论(0编辑  收藏  举报