llllmz

导航

538. 把二叉搜索树转换为累加树c

右根左遍历就行。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
void order(struct TreeNode* root,int * pre){
    if(!root) return;
    order(root->right,pre);
    root->val=root->val+*pre;
    *pre=root->val;
    order(root->left,pre);
}

struct TreeNode* convertBST(struct TreeNode* root) {
    int pre=0;
    order(root,&pre);   
    return root;
}

结果;

posted on 2024-03-07 15:36  神奇的萝卜丝  阅读(27)  评论(0)    收藏  举报