C++ solution using an array


  • 0
    S
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        void in_order(TreeNode* root,vector<TreeNode*>& tv)
        {
            if(root == NULL){
                return;
            }
            in_order(root->left,tv);
            tv.push_back(root);
            in_order(root->right,tv);
        }
        TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
            if(root == NULL)
                return NULL;
            
            vector<TreeNode*> tv;
            in_order(root,tv);
            
            for(int i = 0; i < tv.size(); i++){
                if(p == tv[i] && i != tv.size() - 1){
                    return tv[i+1];
                }
            }
            return NULL;
            
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.