二叉树的下一个结点

题目描述

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

解法

分情况讨论:
1.无右子树:
1.1节点为父节点的左子树,返回父节点
1.2节点为父节点的右子树,直至找到当前结点是其父节点的左子树为止,再返回当前节点的父节点
1.3根节点,返回空
2.有右子树:
则下一个节点为右节点的最左节点

具体实现代码如下:

/*
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)
    {
        if(pNode == null){
            return null;
        }
        //无右子树
        if(pNode.right == null){
            //根节点
            if(pNode.next == null){
                return null;
            }
            //节点为父节点的左子树
            if(pNode == pNode.next.left && pNode.next != null){
                return pNode.next;                
            }
            //节点为父节点的右子树
            else if(pNode == pNode.next.right && pNode.next != null){
                //遍历父结点,直至找到当前结点是其父节点的左子树为止,再返回其父节点
                while(pNode.next != null && pNode != pNode.next.left){
                    pNode = pNode.next;
                }
                return pNode.next;
            }
        }
        //有右子树
        else{
            pNode = pNode.right;
            while(pNode.left != null){
                pNode = pNode.left;
            }
            return pNode;
        }
        return null;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章