class Solution {
public:
    TreeLinkNode* GetNext(TreeLinkNode* pNode) {
        if (pNode->right == nullptr && pNode->next == nullptr)
            return nullptr;
        // 1、右子树不为null 返回右子树左下角
        if (pNode->right != nullptr) {
            pNode = pNode->right;
            while (pNode->left != nullptr) {
                pNode = pNode->left;
            }
            return pNode;
        } else {
            // 2.1、右子树为null而且是父节点的左节点 返回父节点
            if (pNode->next->left == pNode)
                return pNode->next;
            
            // 2.2、右子树为null而且是父节点的右节点
                // 退到父节点
            pNode = pNode->next;
            int flag = 0; // 标志在整个树的左还是右 1: 右
            while (pNode->next) {
                // 当前节点是上一个节点右节点更新flag
                if (pNode->next && pNode->next->right == pNode)
                    flag = 1;
                if (pNode->next && pNode->next->left == pNode)
                    flag = 0;
                pNode = pNode->next;
            }
            // 通过判断flag返回节点
            return flag ? nullptr : pNode;
        }
        return nullptr;
    }
}; 

根据图片代入更容易理解

alt