1. 程式人生 > >二叉樹的下一個結點

二叉樹的下一個結點

class 包含 三種 節點 turn 描述 找到 while solution

題目描述

給定一個二叉樹和其中的一個結點,請找出中序遍歷順序的下一個結點並且返回。註意,樹中的結點不僅包含左右子結點,同時包含指向父結點的指針。 樹見書P275 分三種情況: 1. 該節點有右子樹,下一個結點就是它右子樹的最左節點 2. 該節點沒有右子樹,而且它是父節點的左子節點,則下一個結點是它的父節點 3. 該節點沒有右子樹,而且它是父節點的右子節點,就沿著父節點指針向上遍歷,直到找到一個節點(是自己父節點的左子節點),該節點的父節點就是要找的下一個結點 4. 該節點是全樹最右結點,所以沒有下一個結點了 public class Solution { public TreeLinkNode GetNext(TreeLinkNode pNode) { if (pNode == null) return null; if (pNode.right != null) {//情況1 pNode = pNode.right; while (pNode.left != null) pNode = pNode.left; return pNode; } while(pNode.next != null){ //包括了情況2和3 if(pNode.next.left == pNode) return pNode.next; pNode = pNode.next; } return null;//情況4 } }

二叉樹的下一個結點