zoukankan      html  css  js  c++  java
  • binary tree解题模板

    基础的三个模板:traverse, dc, bst

    【traverse模板】

    题:700. Search in a Binary Search Tree 在bst中返回目标所在的最小子树

    class Solution {
        public TreeNode searchBST(TreeNode root, int val) {
            if (root.val > val)
                return searchBST(root.left, val);
            if (root.val < val)
                return searchBST(root.right, val);
        }
    }

     


    【dc模板】
    题:108 Convert Sorted Array to Binary Search Tree数组变成高度平衡的二叉树

    public TreeNode helper(int[] nums, int low, int high) {
    
    root.left = helper(nums, low, mid - 1);
    root.right = helper(nums, mid + 1, high);
    }

     

    【bst模板】

    题:872. Leaf-Similar Trees 叶子顺序遍历是否相等

     

    private void helper(TreeNode root, ArrayList<Integer> list){
                   
            helper(root.left, list);
            if(root.left == null && root.right == null){
                list.add(root.val);
            }
            helper(root.right, list);
        }

     

     

     

    【左右模板】
    题:对称二叉树 · symmetric binary tree

    public boolean Helper(TreeNode left, TreeNode right) {
    
    return Helper(left.left, right.right) && Helper(left.right, right.left);
    }
    }

     

    【比大小模板】(pruning剪枝法)

    题:938. Range Sum of BST BST的范围总和

    public int helper(TreeNode root, int L, int R) {
    
    if(root.val > R) return rangeSumBST(root.left, L, R);
    if(root.val < L) return rangeSumBST(root.right, L, R);
    }

    【长度模板】
    题:687. Longest Univalue Path 687.最长单值路径

    public int helper(TreeNode node, int value) {
    
    int left = helper(node.left, node.val);
    int right = helper(node.right, node.val);
    
    return Math.max(left, right) + 1;
    }

    题:333. Largest BST Subtree节点数最多的bst子树(子节点的个数就是这么算的)

    public int countNode(TreeNode root) {
    
    return 1 + countNode(root.left) + countNode(root.right);
    }

     

    【具体路径模板】

    public void findBT(TreeNode root, String path, List<String> ans) {
    ans.add(path);
    
    findBT(root.left...);
    findBT(root.right...);
    }

    【判断BST模板】
    题:333. Largest BST Subtree节点数最多的bst子树

    public boolean isValid(TreeNode root, Integer min, Integer max) {
    if (root == null) return true;
    if (min != null && min >= root.val) return false;
    if (max != null && max <= root.val) return false;
    return isValid(root.left, min, root.val) && isValid(root.right, root.val, max);
    }

     

     
  • 相关阅读:
    人物-IT-张志东:张志东
    人物-IT-任正非:任正非
    人物-IT-张朝阳:张朝阳
    院校-清华大学:清华大学
    人物-丁磊:丁磊
    人物-李彦宏:李彦宏
    人物-IT-马云:马云
    inittab
    initlocation
    initdb
  • 原文地址:https://www.cnblogs.com/immiao0319/p/14992981.html
Copyright © 2011-2022 走看看