Leedcode算法专题训练(树)

递归

一棵树要么是空树,要么有两个指针,每个指针指向一棵树。树是一种递归结构,很多树的问题可以使用递归来处理。

1. 树的高度

104. Maximum Depth of Binary Tree (Easy)

Leetcode / 力扣

class Solution {
    public int maxDepth(TreeNode root) {
        if(root==null)return 0;
        return Math.max(maxDepth(root.left),maxDepth(root.right))+1;
    }
}

2. 平衡树

110. Balanced Binary Tree (Easy)

Leetcode / 力扣

    3
   / \
  9  20
    /  \
   15   7

平衡树左右子树高度差都小于等于 1
 

class Solution {
    public boolean result=true;
    public boolean isBalanced(TreeNode root) {
        if(root==null)return true;
        if(Math.abs(depth(root.left)-depth(root.right))>1)return false;
        return isBalanced(root.left)&&isBalanced(root.right);
    }
    public int depth(TreeNode root){
        if(root==null)return 0;
        return Math.max(depth(root.left),depth(root.right))+1;
    }
}

3. 两节点的最长路径

543. Diameter of Binary Tree (Easy)

Leetcode / 力扣

Input:

         1
        / \
       2  3
      / \
     4   5

Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
class Solution {
    private int max = 0;
    public int diameterOfBinaryTree(TreeNode root) {
        depth(root);
        return max;
    }
    
    private int depth(TreeNode root) {
        if (root == null) return 0;
        int leftDepth = depth(root.left);
        int rightDepth = depth(root.right);
        max = Math.max(max, leftDepth + rightDepth);
        return Math.max(leftDepth, rightDepth) + 1;
    }

}

4. 翻转树

226. Invert Binary Tree (Easy)

Leetcode / 力扣

class Solution {
    public TreeNode invertTree(TreeNode root) {
        if(root==null)return null;
        TreeNode tmp=root.left;
        root.left=root.right;
        root.right=tmp;
        invertTree(root.left);
        invertTree(root.right);
        return root;
    }
}

5. 归并两棵树

617. Merge Two Binary Trees (Easy)

Leetcode / 力扣

Input:
       Tree 1                     Tree 2
          1                         2
         / \                       / \
        3   2                     1   3
       /                           \   \
      5                             4   7

Output:
         3
        / \
       4   5
      / \   \
     5   4   7
class Solution {
    public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
        if(t1==null&&t2==null)return null;
        if(t1==null)return t2;
        if(t2==null)return t1;
        TreeNode root =new TreeNode(t1.val+t2.val);
        root.left=mergeTrees(t1.left,t2.left);
        root.right=mergeTrees(t1.right,t2.right);
        return root;
    }
}

6. 判断路径和是否等于一个数

Leetcdoe : 112. Path Sum (Easy)

Leetcode / 力扣

Given the below binary tree and sum = 22,

              5
             / \
            4   8
           /   / \
          11  13  4
         /  \      \
        7    2      1

return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        if(root==null)return false;
        if(root.left == null && root.right == null){
            return root.val == sum;
        }
        return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
    }
}

113. 路径总和 II

class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> result=new ArrayList<>();
        dfs(root,sum,new ArrayList<>(),result);
        return result;
    }
    private void dfs(TreeNode root,int sum,List<Integer> list,List<List<Integer>>result){
        if(root==null){
            return;
        }
        list.add(root.val);
        if(root.left==null&&root.right==null&&sum==root.val){
            result.add(new ArrayList(list));
        }
        dfs(root.left,sum-root.val,list,result);
        dfs(root.right,sum-root.val,list,result);
        list.remove(list.size() - 1);
    }
}
}

7. 统计路径和等于一个数的路径数量

437. Path Sum III (Easy)

Leetcode / 力扣

java 双重递归 思路:首先先序递归遍历每个节点,再以每个节点作为起始点递归寻找满足条件的路径。

class Solution {
    public int pathSum(TreeNode root, int sum) {
        if(root==null)return 0;
        int result=countPath(root,sum);
        int a=pathSum(root.left,sum);
        int b=pathSum(root.right,sum);
        return result+a+b;
    }
    public int countPath(TreeNode root,int sum){
        if(root==null){
            return 0;
        }
        sum=sum-root.val;
        int result=sum==0?1:0;
        return result+countPath(root.left,sum)+countPath(root.right,sum);
    }
}

8. 子树

572. Subtree of Another Tree (Easy)

Leetcode / 力扣

class Solution {
    public boolean isSubtree(TreeNode s, TreeNode t) {
    if (s == null) return false;
    return isSubtreeWithRoot(s, t) || isSubtree(s.left, t) || isSubtree(s.right, t);
}

    private boolean isSubtreeWithRoot(TreeNode s, TreeNode t) {
         if(t==null&&s==null)return true;
        if(t==null||s==null)return false;
        if(t.val != s.val)return false;
        return isSubtreeWithRoot(s.left, t.left) && isSubtreeWithRoot(s.right, t.right);
    }
}

9. 树的对称

101. Symmetric Tree (Easy)

Leetcode / 力扣

    1
   / \
  2   2
 / \ / \
3  4 4  3
class Solution {
    public boolean isSymmetric(TreeNode root) {
        if(root==null)return true;
        return isSymmetrictree(root.left,root.right);
    }

     private boolean isSymmetrictree(TreeNode left,TreeNode right){
        if(left==null&&right==null)return true;
        if(left==null||right==null)return false;
        if(left.val!=right.val)return false;
        return isSymmetrictree(left.left,right.right)&&isSymmetrictree(left.right,right.left);
    }
}

10. 最小路径

111. Minimum Depth of Binary Tree (Easy)

Leetcode / 力扣

树的根节点到叶子节点的最小路径长度

public int minDepth(TreeNode root) {
    if (root == null) return 0;
    int left = minDepth(root.left);
    int right = minDepth(root.right);
    if (left == 0 || right == 0) return left + right + 1;
    return Math.min(left, right) + 1;
}

11. 统计左叶子节点的和

404. Sum of Left Leaves (Easy)

Leetcode / 力扣

解题思路
1、终止条件,root == null时,返回0;
2、如果当前节点是左节点,并且无子节点,累加对应节点的val值;
3、继续搜索左右子树,直到root == null,即最后一个节点。

class Solution {
    private int res=0;
    public int sumOfLeftLeaves(TreeNode root) {
        if(root==null){
            return 0;
        }
        if(root.left!=null&&root.left.left==null&&root.left.right==null){
            res+=root.left.val;
        }
        sumOfLeftLeaves(root.left);
        sumOfLeftLeaves(root.right);
        return res;

    }
}

12. 相同节点值的最大路径长度

687. Longest Univalue Path (Easy)

Leetcode / 力扣

             1
            / \
           4   5
          / \   \
         4   4   5

Output : 2
class Solution {
    int ans;
    public int longestUnivaluePath(TreeNode root) {
        ans = 0;
        longestPath(root);
        return ans;
    }
    //递归函数功能:搜寻以node为起点的最长同值路径:要么是以node为起点的左子树,要么是以node为起点的右子树
    public int longestPath(TreeNode node) {
        if (node == null) return 0;
        int maxLorRres=0;
        int left = longestPath(node.left); //node左子树的最长同值路径
        int right = longestPath(node.right);//node右子树的最长同值路径
        //这种情况对于寻找最长同值路径长有帮助,对于搜索以root为路径起始点的最长路径没有帮助
        if (node.left != null && node.left.val == node.val&&node.right != null && node.right.val == node.val) {
            ans=Math.max(ans, left + right+2);
        }
        //从左右子树中选择最长的同值路径
        if(node.left!=null&&node.left.val == node.val){
            maxLorRres=left+1;
        }
        if(node.right!=null&&node.right.val==node.val){
            maxLorRres=Math.max(maxLorRres,right+1);
        }
        //从ans与maxLorRres中更新最大值
        ans=Math.max(ans,maxLorRres);
        return maxLorRres; //所以你能知道为什么返回这个值了吗?
    }

}
private int path = 0;

public int longestUnivaluePath(TreeNode root) {
    dfs(root);
    return path;
}

private int dfs(TreeNode root){
    if (root == null) return 0;
    int left = dfs(root.left);
    int right = dfs(root.right);
    int leftPath = root.left != null && root.left.val == root.val ? left + 1 : 0;
    int rightPath = root.right != null && root.right.val == root.val ? right + 1 : 0;
    path = Math.max(path, leftPath + rightPath);
    return Math.max(leftPath, rightPath);
}

13. 间隔遍历

337. House Robber III (Medium)

Leetcode / 力扣

     3
    / \
   2   3
    \   \
     3   1
Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
class Solution {
    public int rob(TreeNode root) {
        if(root==null)return 0;
        int val1=root.val;
        if(root.left!=null)val1+=rob(root.left.left)+rob(root.left.right);
        if(root.right!=null)val1+=rob(root.right.left) + rob(root.right.right);
        int val2 = rob(root.left) + rob(root.right);
        return Math.max(val1, val2);
    }
}

14. 找出二叉树中第二小的节点

671. Second Minimum Node In a Binary Tree (Easy)

Leetcode / 力扣

Input:
   2
  / \
 2   5
    / \
    5  7

Output: 5
class Solution {
    public int findSecondMinimumValue(TreeNode root) {
     return traversal(root,root.val);
    }
    
    private int traversal(TreeNode root,int value){
        if(root == null){
            return -1;
        }
        if(root.val > value){
            return root.val;
        }
        // 寻找左右子节点中,第一个大于自己的节点
        int l = traversal(root.left,value);
        int r = traversal(root.right,value);

        // 存在两个子节点
        if(l>=0 && r>=0){
            return Math.min(l,r);
        }
        // 存在0个子节点
        return Math.max(l,r);
    }
  
}

层次遍历

使用 BFS 进行层次遍历。不需要使用两个队列来分别存储当前层的节点和下一层的节点,因为在开始遍历一层的节点时,当前队列中的节点数就是当前层的节点数,只要控制遍历这么多节点数,就能保证这次遍历的都是当前层的节点。

1. 一棵树每层节点的平均数

637. Average of Levels in Binary Tree (Easy)

Leetcode / 力扣

class Solution {
    public List<Double> averageOfLevels(TreeNode root) {
        List<Double> result=new ArrayList<>();
        if(root==null)return result;
        Queue<TreeNode>queue=new LinkedList<>();
        queue.add(root);
        while(!queue.isEmpty()){
            double sum=0;
            int length=queue.size();
            for(int i=queue.size();i>0;i--){
                TreeNode temp=queue.poll();
                sum+=temp.val;
                if(temp.left!=null)queue.add(temp.left);
                if(temp.right!=null)queue.add(temp.right);
            }
            result.add(sum/length);
        }
        return result;
    }
}

2. 得到左下角的节点

513. Find Bottom Left Tree Value (Easy)

Leetcode / 力扣

Input:

        1
       / \
      2   3
     /   / \
    4   5   6
       /
      7

Output:
7
class Solution {
    public int findBottomLeftValue(TreeNode root) {
        if(root==null)return 0;
        Queue<TreeNode> queue=new LinkedList<>();
        queue.add(root);
        int result=0;
        while(!queue.isEmpty()){
            TreeNode temp=queue.poll();
            result=temp.val;
            if (temp.right != null) queue.add(temp.right);
            if (temp.left != null) queue.add(temp.left);
        }
        return result;
    }
}

前中后序遍历

    1
   / \
  2   3
 / \   \
4   5   6
  • 层次遍历顺序:[1 2 3 4 5 6]
  • 前序遍历顺序:[1 2 4 5 3 6]
  • 中序遍历顺序:[4 2 5 1 3 6]
  • 后序遍历顺序:[4 5 2 6 3 1]

层次遍历使用 BFS 实现,利用的就是 BFS 一层一层遍历的特性;而前序、中序、后序遍历利用了 DFS 实现。

前序、中序、后序遍只是在对节点访问的顺序有一点不同,其它都相同。

① 前序

void dfs(TreeNode root) {
    visit(root);
    dfs(root.left);
    dfs(root.right);
}

② 中序

void dfs(TreeNode root) {
    dfs(root.left);
    visit(root);
    dfs(root.right);
}

③ 后序

void dfs(TreeNode root) {
    dfs(root.left);
    dfs(root.right);
    visit(root);
}

1. 非递归实现二叉树的前序遍历

144. Binary Tree Preorder Traversal (Medium)

Leetcode / 力扣

class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> list=new ArrayList<>();
        Stack<TreeNode> stack=new Stack<>();
        while(root!=null||(!stack.empty())){
            if(root!=null){
                list.add(root.val);//步骤一,取根节点的值
                stack.push(root);//把根节点放入栈中
                root=root.left;//步骤二,遍历左子树
            }
            else{
                TreeNode tem=stack.pop();
                root=tem.right;//步骤三,遍历右子树
            }
        }
        return list;
    }
}

2. 非递归实现二叉树的中序遍历

94. Binary Tree Inorder Traversal (Medium)

Leetcode / 力扣

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list=new ArrayList<>();
        Stack<TreeNode> stack=new Stack<>();
        while(root!=null||(!stack.empty())){
            if(root!=null){
                stack.push(root);//把根节点放入栈中
                root=root.left;//步骤一,遍历左子树
            }
            else{
                TreeNode tem=stack.pop();
                list.add(tem.val);//步骤二,取根结点的值
                root=tem.right;//步骤三,遍历右子树
            }
        }
        return list;
    }
}

3. 非递归实现二叉树的后序遍历

145. Binary Tree Postorder Traversal (Medium)

Leetcode / 力扣

class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> list=new ArrayList<>();
        Stack<TreeNode> stack=new Stack<>();
        while(root!=null||(!stack.empty())){
            if(root!=null){
             stack.push(root);//把根节点放入栈中
             list.add(0,root.val);//步骤一,在index=0处插入根结点的值
             root=root.right;//步骤二,遍历右子树
            }
            else{
                TreeNode tem=stack.pop();
                root=tem.left;//步骤三,遍历左子树
            }
        }
        return list;
    }
}

BST

二叉查找树(BST):根节点大于等于左子树所有节点,小于等于右子树所有节点。

二叉查找树中序遍历有序。

1. 修剪二叉查找树

669. Trim a Binary Search Tree (Easy)

Leetcode / 力扣

class Solution {
    public TreeNode trimBST(TreeNode root, int low, int high) {
        if(root==null)return root;
        if(root.val>high)return trimBST(root.left,low,high);
        if(root.val<low)return trimBST(root.right,low,high);

        root.left=trimBST(root.left,low,high);
        root.right=trimBST(root.right,low,high);
        return root;
    }
}

2. 寻找二叉查找树的第 k 个元素

230. Kth Smallest Element in a BST (Medium)

Leetcode / 力扣

中序遍历解法:

class Solution {
    private int val;
    private int cnt=0;
    public int kthSmallest(TreeNode root, int k) {
        inOrder(root,k);
        return val;
    }

    private void inOrder(TreeNode node,int k){
        if(node==null)return;
        inOrder(node.left,k);
        cnt++;
        if(cnt==k){
          val=node.val;
          return;  
        }
        inOrder(node.right,k);

    }
}
class Solution {
    public int kthSmallest(TreeNode root, int k) {
        Stack<TreeNode>stack=new Stack<>();
        while(true){
            while(root!=null){
                stack.add(root);
                root=root.left;
            }
            root=stack.pop();
            if(--k==0)return root.val;

            root=root.right;
        }
    }
}

3. 把二叉查找树每个节点的值都加上比它大的节点的值

Convert BST to Greater Tree (Easy)

Leetcode / 力扣

Input: The root of a Binary Search Tree like this:

              5
            /   \
           2     13

Output: The root of a Greater Tree like this:

             18
            /   \
          20     13
class Solution {
    int sum=0;
    public TreeNode convertBST(TreeNode root) {
        if(root==null)return null;
        convertBST(root.right);
        sum+=root.val;
        root.val=sum;
        convertBST(root.left);
        return root;
    }
}

4. 二叉查找树的最近公共祖先

235. Lowest Common Ancestor of a Binary Search Tree (Easy)

Leetcode / 力扣

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root==null)return null;
        if(root.val>p.val&&root.val>q.val)return lowestCommonAncestor(root.left,p,q);
        else if(root.val<p.val&&root.val<q.val)return lowestCommonAncestor(root.right,p,q);
        return root;
    }
}

5. 二叉树的最近公共祖先

236. Lowest Common Ancestor of a Binary Tree (Medium)

Leetcode / 力扣

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root==null||root==p||root==q)return root;
        TreeNode left=lowestCommonAncestor(root.left,p,q);
        TreeNode right=lowestCommonAncestor(root.right,p,q);
        if(left!=null&&right!=null)return root;
        else if(left!=null&&right==null)return left;
        else return right;
    }
}

6. 从有序数组中构造二叉查找树

108. Convert Sorted Array to Binary Search Tree (Easy)

Leetcode / 力扣

class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        return helper(nums,0,nums.length-1);
    }

    public TreeNode helper(int[] nums,int lo,int hi){
        if(lo>hi){
            return null;
        }
        int mid=lo+(hi-lo)/2;
        TreeNode root=new TreeNode(nums[mid]);
        root.left=helper(nums,lo,mid-1);
        root.right=helper(nums,mid+1,hi);
        return root;
    }
}

7. 根据有序链表构造平衡的二叉查找树

109. Convert Sorted List to Binary Search Tree (Medium)

Leetcode / 力扣

class Solution {
    public TreeNode sortedListToBST(ListNode head) {
        if(head==null)return null;
        if(head.next==null)return new TreeNode(head.val);
        ListNode pre=null,fast=head,slow=head;
        while(fast!=null&&fast.next!=null){
            pre=slow;
            slow=slow.next;
            fast=fast.next.next;
        }
        pre.next=null;
        TreeNode root=new TreeNode(slow.val);
        root.left=sortedListToBST(head);
        root.right=sortedListToBST(slow.next);
        return root; 
    }
}

8. 在二叉查找树中寻找两个节点,使它们的和为一个给定值

653. Two Sum IV - Input is a BST (Easy)

Leetcode / 力扣

public class Solution {
    public boolean findTarget(TreeNode root, int k) {
        Set < Integer > set = new HashSet();
        return find(root, k, set);
    }
    public boolean find(TreeNode root, int k, Set < Integer > set) {
        if (root == null)
            return false;
        if (set.contains(k - root.val))
            return true;
        set.add(root.val);
        return find(root.left, k, set) || find(root.right, k, set);
    }
}

9. 在二叉查找树中查找两个节点之差的最小绝对值

这题的难点在于思考前向节点如何表示,还有BST的特性不难

530. Minimum Absolute Difference in BST (Easy)

Leetcode / 力扣

class Solution {
    int abs_min=Integer.MAX_VALUE;
    TreeNode pre;
    public int getMinimumDifference(TreeNode root) {
        if(root==null)return 0;
        inOrder(root);
        return abs_min;
    }

    private void inOrder(TreeNode node){
        if(node==null)return;
        inOrder(node.left);
        if(pre!=null) abs_min=Math.min(abs_min,node.val-pre.val);
        pre=node;
        inOrder(node.right);
    }
}

10. 寻找二叉查找树中出现次数最多的值

501. Find Mode in Binary Search Tree (Easy)

Leetcode / 力扣

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int preVal = 0, curTimes = 0, maxTimes = 0;
    ArrayList<Integer> list = new ArrayList<Integer>();
    public int[] findMode(TreeNode root) {
	traversal(root);
	//list转换为int[]
	int size = list.size();
	int[] ans = new int[size];
	for(int i = 0; i < size; i++){
	    ans[i] = list.get(i);
	}
	return ans;
    }
    //二叉搜索树中序遍历是递增顺序
    public void traversal(TreeNode root){
        if(root != null){
            traversal(root.left);
            //判断当前值与上一个值的关系, 更新 curTimes 和 preVal
            if(preVal == root.val){
                curTimes++;
            }else{
                preVal = root.val;
                curTimes = 1;
            }
            //判断当前数量与最大数量的关系, 更新 list 和 maxTimes
            if(curTimes == maxTimes){
                list.add(root.val);
            }else if(curTimes > maxTimes){
                list.clear();
                list.add(root.val);
                maxTimes = curTimes;
            }
            traversal(root.right);
        }
    }
}

Trie

Trie,又称前缀树或字典树,用于判断字符串是否存在或者是否具有某种字符串前缀。

1. 实现一个 Trie

208. Implement Trie (Prefix Tree) (Medium)

Leetcode / 力扣

这个题目的关键是数组的用法,就是说建立一个对象,对象中的数组进行实例化,不断进入对象的孩子数组中再进行实例化

class TrieNode{
    TrieNode[] child;
    boolean isEnd;
    public TrieNode(){
        child=new TrieNode[26];
        isEnd=false;
    }
}


class Trie {
    TrieNode root;

    /** Initialize your data structure here. */
    public Trie() {
        root=new TrieNode();
    }

    /** Inserts a word into the trie. */
    public void insert(String word) {
        TrieNode cur=root;
        for(int i=0;i<word.length();i++){
            char c=word.charAt(i);
            if(cur.child[c-'a']==null){
                cur.child[c-'a']=new TrieNode();
            }
            cur=cur.child[c-'a'];
        }
        cur.isEnd=true;
    }
    
    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        TrieNode cur=root;
        for(int i=0;i<word.length();i++){
            char c=word.charAt(i);
            if(cur.child[c-'a']==null){
                return false;
            }
            cur=cur.child[c-'a'];
        }
        return cur.isEnd;
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        TrieNode cur=root;
        for(int i=0;i<prefix.length();i++){
            char c=prefix.charAt(i);
            if(cur.child[c-'a']==null){
                return false;
            }
            cur=cur.child[c-'a'];
        }
        return true;

    }
}

hashmap的是实现

class TrieNode{
    HashMap<Character,TrieNode> next=new HashMap<>();
    boolean isEnd;
    public TrieNode(){
        isEnd=false;
    }
}

class Trie {
    TrieNode root;

    /** Initialize your data structure here. */
    public Trie() {
        root=new TrieNode();
    }

    /** Inserts a word into the trie. */
    public void insert(String word) {
        TrieNode cur=root;
        for(int i=0;i<word.length();i++){
            char c=word.charAt(i);
            if(!cur.next.containsKey(c)){
                cur.next.put(c,new TrieNode());
            }
            cur=cur.next.get(c);
        }
        cur.isEnd=true;
    }
    
    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        TrieNode cur=root;
        for(int i=0;i<word.length();i++){
            char c=word.charAt(i);
            if(!cur.next.containsKey(c)){
                return false;
            }
            cur=cur.next.get(c);
        }
        return cur.isEnd;
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        TrieNode cur=root;
        for(int i=0;i<prefix.length();i++){
            char c=prefix.charAt(i);
            if(!cur.next.containsKey(c)){
                return false;
            }
            cur=cur.next.get(c);
        }
        return true;

    }
}

2. 实现一个 Trie,用来求前缀和

677. Map Sum Pairs (Medium)

Leetcode / 力扣

class MapSum {
    class TrieNode{
        TrieNode[] children;
        int value;
        public TrieNode(){
            children=new TrieNode[26];
        }
    }

    private TrieNode root;

    /** Initialize your data structure here. */
    public MapSum() {
        root=new TrieNode();
    }
    
    public void insert(String key, int val) {
        TrieNode node=root;
        char[] charArray=key.toCharArray();
        for(int i=0;i<charArray.length;i++){
            int idx=charArray[i]-'a';
            if(node.children[idx]==null){
                node.children[idx]=new TrieNode();
            }
            node=node.children[idx];
        }
        node.value=val;
    }
    
    public int sum(String prefix) {
        if(prefix==null)return 0;
        TrieNode node=root;
        char[] charArray=prefix.toCharArray();
        for(int i=0;i<charArray.length;i++){
            int idx=charArray[i]-'a';
            if(node.children[idx]==null)return 0;
            node=node.children[idx];
        }
        return dfs(node);

    }

    private int dfs(TrieNode node){
        if(node==null)return 0;
        int res=node.value;
        for(TrieNode child:node.children){
            res+=dfs(child);
        }
        return res ;
    }
}

/**
 * Your MapSum object will be instantiated and called as such:
 * MapSum obj = new MapSum();
 * obj.insert(key,val);
 * int param_2 = obj.sum(prefix);
 */

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值