7.1 leetcode 刷题记录(tree)938BST、94(medium)inorder traversal、102(medium)BFS

1.巩固关于binary search tree(BST,二叉搜索树)的相关知识。

每个node的值大于left subtree中所有nodes的值,小于right subtree中所有nodes的值。

leetcode 938. Range Sum of BST

Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive).

The binary search tree is guaranteed to have unique values.

思路:

traverse the tree using a depth first search. If the value is between L and R, add it to sum.

P.S: Recursion cannot be in if clause. Because although the key of the node  is smaller L, the key of the node's right child can be lagger than L.

class Solution {
    int sum=0;
    public int rangeSumBST(TreeNode root, int L, int R) {
        if(root!=null){
            if(root.val>=L & root.val<= R){
                sum=sum+root.val;
            }
            rangeSumBST(root.left,L,R);
            rangeSumBST(root.right,L,R);
        }
        return sum;
    }
}


The way to optimize the algorithm:

if the key of the node  is smaller than L, we can just traverse the right subtree of the node.

class Solution {
    int sum=0;
    public int rangeSumBST(TreeNode root, int L, int R) {
        if(root!=null){
            if(root.val>=L & root.val<= R){
                sum=sum+root.val;
                rangeSumBST(root.left,L,R);
                rangeSumBST(root.right,L,R);
            }
            if(root.valR){
                rangeSumBST(root.left,L,R);
            }
            //rangeSumBST(root.left,L,R);
            //rangeSumBST(root.right,L,R);
        }
        return sum;
    }
}

2.树的遍历

preorder traversal : root->left subtree->right subtree

inorder traversal: left subtree->root->right subtree

postorder traversal: left subtree->right subtree->root

94. Binary Tree Inorder Traversal

Given a binary tree, return the inorder traversal of its nodes' values.

PS: the variable res should be a global variable.

class Solution {
    List  res=new ArrayList<> ();
    public List inorderTraversal(TreeNode root) {
        
        if(root!=null){
            inorderTraversal(root.left);
            res.add(root.val);
            inorderTraversal(root.right);
        }
        return res;
    }
}

3.树的广度优先搜索

使用队列(queue),队列是先进先出

102. Binary Tree Level Order Traversal

Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

class Solution {
    public List> levelOrder(TreeNode root) {
        List> res=new LinkedList>();
        Queue queue=new LinkedList();
        if(root==null) return res;
        
        queue.add(root);
        
        while(!queue.isEmpty()){
            int count=queue.size();
            List level= new LinkedList<>();
            for(int i=0;i

 

你可能感兴趣的:(tree,BST,leetcode,刷题,刷题,leetcode,tree,BST)