题目
解法:中序遍历,保存上一个节点的值,如果上一个节点值大于当前节点值,保存上一个节点的值,同时保存最后一个上一个节点大于当前节点值下的当前节点值,作为结果输出
时间复杂度O(n),空间复杂度O(1)
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
/**
*
* @param root TreeNode类 the root
* @return int整型vector
*/
vector<int> findError(TreeNode* root) {
// write code here
//中序遍历
dfs(root);
return res;
}
void dfs(TreeNode* root)
{
if(root==nullptr)return;
dfs(root->left);
if(index==1 && root->val<tmp)
{
res[index]=tmp;
index--;
}
if(index==0 && root->val<tmp)
{
res[index]=root->val;
}
tmp=root->val;
dfs(root->right);
}
private:
int tmp=INT_MIN,index=1;
vector<int>res{0,0};
};
京公网安备 11010502036488号