[剑指offer] 二叉树的下一个节点

不容易一次写对的题,对指针的操作要细心。

/*
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 == NULL) {
            return NULL;
        }
        
        // 如果pNode有右子树,就找右子树的最左下方的节点
        if (pNode->right != NULL) {
            TreeLinkNode* next = pNode->right;
            while (next->left != NULL) {
                next = next->left;
            }
            return next;
        }
        
        // pNode无右子树,无父节点,返回NULL
        if (pNode->next == NULL) {
            return NULL;
        }
        
        // pNode无右子树,但是pNode是父节点的左孩子,就返回父节点
        if (pNode == pNode->next->left) {
            return pNode->next;
        }
        
        // pNode无右子树,是父节点的右孩子,就一直往上找,直到找到一个节点是其父节点的左孩子,返回该节点的父节点
        TreeLinkNode* cur = pNode;
        while (cur->next != NULL && cur != cur->next->left) {
            cur = cur->next;
        }
        return cur->next;
    }
};
原文地址:https://www.cnblogs.com/ilovezyg/p/7589102.html