当前位置:网站首页>538. convert binary search tree to cumulative tree

538. convert binary search tree to cumulative tree

2022-06-11 06:29:00 Saucey_ six

subject :
 Insert picture description here
Answer key :
Ideas : Reverse middle order traversal of binary search tree .
Code :

var convertBST = function (root) {
    var start = 0;// Initially set to 0
    var arr = [];
    var p = root;

    while (p || arr.length) {
        while (p) {
            arr.push(p)// Store the values of the right subtree 
            p = p.right// Traverse the right subtree of the right subtree 
        }

        p = arr.pop(p)// Perform iterative accumulation 
        p.val += start;
        start = p.val;
        p = p.left// After traversing the right subtree, traverse the left subtree 
    }
    return root
};

ps: the second day

原网站

版权声明
本文为[Saucey_ six]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206110623219925.html