劍指offer-二叉樹的下一個節點

劍指offer-二叉樹的下一個節點

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


解題思路
其實這道題很簡單的,中序遍歷的下一個節點嘛
1.該節點有右節點,就是該右節點的最左節點,一直到找左節點
2.如果沒有就找父節點,沒有父節點就只說明沒有下一個節點
3.如果該節點是從父節點一直找右節點下去的最後一個右節點,說明沒有下個節點 4.如果是某個左子樹的最右節點,說明該左子樹的根節點就是下一個節點
/*
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)
        {
            while(pNode.next!=null)
            {
                if(pNode.next.left==pNode)
                    return pNode.next;
                if(pNode.next.right==pNode)
                    pNode=pNode.next;
            }
            if(pNode.next==null)
                return null;
        }
         TreeLinkNode p=pNode.right;
         while(p.left!=null)
            p=p.left;
         return p;
        
        
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章