【LeetCode】99. 恢復二叉搜尋樹 結題報告 (C++)
阿新 • • 發佈:2018-11-11
原題地址:https://leetcode-cn.com/problems/recover-binary-search-tree/description/
題目描述:
二叉搜尋樹中的兩個節點被錯誤地交換。
請在不改變其結構的情況下,恢復這棵樹。
示例 1:
輸入: [1,3,null,null,2]
1
/
3
\
2
輸出: [3,1,null,null,2]
3
/
1
\
2
示例 2:
輸入: [3,1,4,null,null,2]
3
/ \
1 4
/
2
輸出: [2,1,4,null,null,3]
2
/ \
1 4
/
3
進階:
使用 O(n) 空間複雜度的解法很容易實現。
解題方案:
對二叉樹進行中序遍歷,預期的結果為從小到大排序的數列
參考地址:https://blog.csdn.net/a45872055555/article/details/38685035
/** * 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 recoverTree(TreeNode *root) { if(root == NULL) return ; InOrderTraverse(root); } void InOrderTraverse(TreeNode *root){ stack<TreeNode *> S; TreeNode *p = root; vector<int> num; TreeNode *tmp = NULL; TreeNode *big = NULL; TreeNode *small = NULL; bool flag = false; while(p || !S.empty()){ if(p){ S.push(p); p = p->left; }else{ p = S.top(); S.pop(); if(tmp == NULL){ tmp = p; p = p->right; continue; } if(!flag){ if(tmp->val > p->val){ big = tmp; small = p; flag = true; } }else{ if(tmp->val > p->val){ small = p; break; } } tmp = p; p = p->right; } } int a = big->val; big->val = small->val; small->val = a; } };