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);
    }
}

 灵活地加参数,来精确地求下一层节点:https://www.cnblogs.com/immiao0319/p/15260813.html

remove duplicates from unsorted binary tree 既然是随意一棵树,写出个基本模板就行了

https://stackoverflow.com/questions/20013384/delete-duplicates-from-binary-tree

void travel(Node* root, int parentNode)
{
   if(root == NULL)
      return;
   if(root.val == parentNode)
      deleteNode(root, root.val) //method to remove node from BST
   travel(root.left, root.val);
   tarvel(root.right,root.val);
}

tarvel(root, INT_MIN);

 


【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);
}

 

posted @ 2021-07-10 04:17  苗妙苗  阅读(93)  评论(0编辑  收藏  举报