Um Leetcode por dia-938. Âmbito da árvore de pesquisa binária e [travessia em ordem]

Insira a descrição da imagem aqui
Ideia principal: travessia em ordem

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    
    
    int ans = 0;
    public int rangeSumBST(TreeNode root, int low, int high) {
    
    
        if(root==null) return 0;
        rangeSumBST(root.left,low,high);
        if(root.val>=low){
    
    
            if(root.val<=high){
    
    
                ans+=root.val;
            }else{
    
    
                return ans;
            }
        }
        rangeSumBST(root.right,low,high);
        return ans;
    }
    
}

Acho que você gosta

Origin blog.csdn.net/weixin_41041275/article/details/111468002
Recomendado
Clasificación