538. Convert BST to Greater Tree

538. Convert BST to Greater Tree_第1张图片

利用树遍历的有序性:中序遍历。当然,递归和非递归的想法总是合理的。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private int sum = 0;
    public TreeNode convertBST(TreeNode root) {
        if(root != null) {
           convertBST(root.right);
           root.val += sum;
           sum = root.val;
           convertBST(root.left);
        }
        return root;
    }
}
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode convertBST(TreeNode root) {
        if(root == null){
            return root;
        }
        
        TreeNode node = root;
        
        Stack stack = new Stack<>();
        TreeNode preNode = null;
        
        while(!stack.isEmpty() || node!=null){
            while(node!=null){
                stack.push(node);
                node = node.right;
            }
            
            node = stack.pop();
            if(preNode != null){
                node.val += preNode.val;
            }
            preNode = node;            
            node = node.left;
        }
        
        return root;
    }
    
}

 

你可能感兴趣的:(深度优先搜索,树)