0538.cpp (464B)
1 class Solution { 2 public: 3 TreeNode *convertBST(TreeNode *root) { 4 TreeNode *head = root; 5 stack<TreeNode *> st; 6 int sum = 0; 7 while (true) { 8 while (root) { 9 st.push(root); 10 root = root->right; 11 } 12 if (st.empty()) break; 13 root = st.top(), st.pop(); 14 sum = root->val += sum; 15 root = root->left; 16 } 17 return head; 18 } 19 };