1. 程式人生 > 實用技巧 >劍指Offer 8:二叉樹的下一個結點

劍指Offer 8:二叉樹的下一個結點

/*
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){ TreeLinkNode tmp = pNode.right; while(tmp.left!=null){ tmp = tmp.left; } return tmp; } //若左子樹為空,則依次向上遍歷其父節點,直到某個節點是其父節點的左子樹
TreeLinkNode tmp = pNode; while(tmp.next!=null){ if(tmp.next.left==tmp){ return tmp.next; } tmp = tmp.next; } return null; } }