二叉樹的下一個結點

題目描述

給定一個二叉樹和其中的一個結點,請找出中序遍歷順序的下一個結點並且返回。注意,樹中的結點不僅包含左右子結點,同時包含指向父結點的指針。

解法

分情況討論:
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;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章