C++ easily understandable code


  • 0
    A
        TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
            if(preorder.size() == 0) return nullptr;
            map < int, int > positionOfNode;
            for(int i = 0; i < inorder.size(); i++) {
                positionOfNode[inorder[i]] = i;
            }
            TreeNode *root = new TreeNode(preorder[0]);
            for(int i = 1; i < preorder.size(); i++) {
                TreeNode *newNode = new TreeNode(preorder[i]);
                TreeNode* iter = root;
                while(iter) {
                    if(positionOfNode[preorder[i]] < positionOfNode[iter -> val]) {
                        if(iter -> left == nullptr) {
                            iter -> left = newNode;
                            break;
                        }
                        iter = iter -> left;
                    }                    
                    else {
                        if(iter -> right == nullptr) {
                            iter -> right = newNode;
                            break;
                        }
                        iter = iter -> right;
                    }
                }
            }
            return root;
        }
    

Log in to reply
 

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