《劍指offer》二叉樹的下一個結點,《劍指offer》二叉樹

來源:互聯網
上載者:User

《劍指offer》二叉樹的下一個結點,《劍指offer》二叉樹

【 聲明:著作權,轉載請標明出處,請勿用於商業用途。  聯絡信箱:libin493073668@sina.com】


題目連結:http://www.nowcoder.com/practice/9023a0c988684a53960365b889ceaf5e?rp=3&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking


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

思路

我們通過畫一個二叉樹來觀察特點,很明顯要尋找滿足題意特點的下一個結點滿足以下條件。

1.如果一個結點有右子樹,那麼其下一個結點就是右子樹中最左的結點

2.如果一個結點沒有右子樹,同時該結點是父結點的左子結點,那麼其下一個結點就是父結點

3.如果一個結點既沒有右子樹,而且還是父結點的右子結點,那麼我們就要沿著父結點一層層往上遍曆,直到找到一個新結點是其父結點的左子結點的時候,那麼這個新結點的父結點就是我們要求的結點。


using namespace std;/*struct TreeLinkNode {    int val;    struct TreeLinkNode *left;    struct TreeLinkNode *right;    struct TreeLinkNode *next;    TreeLinkNode(int x) :val(x), left(NULL), right(NULL), next(NULL) {    }};*/class Solution{public:TreeLinkNode* GetNext(TreeLinkNode* pNode){if(pNode==nullptr)return nullptr;if(pNode->right!=nullptr){TreeLinkNode *pRight = pNode->right;while(pRight->left!=nullptr)pRight = pRight->left;return pRight;}else if(pNode->next!=nullptr){TreeLinkNode *pCurNode = pNode;TreeLinkNode *pParent = pNode->next;while(pParent!=nullptr && pCurNode == pParent->right){pCurNode = pParent;pParent = pParent->next;}return pParent;}}};


著作權聲明:本文為博主原創文章,如果轉載,請註明出處

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.