about Binary Tree

Tue, Feb 16, 2021 2-minute read

learning binary tree

Use java to realize a simple Customer Account project.

image

binary treel level order

image

binary treel level order

image

binary treel level order

class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        

        List<List<Integer>> res = new ArrayList<List<Integer>>();
        Queue<TreeNode> q = new ArrayDeque<>();
        
        if (root != null) {
            q.add(root);
        }

        while(!q.isEmpty()) {
            int size = q.size();
            List<Integer> list = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode node = q.poll();
                list.add(node.val);
                if (node.left != null) {
                    q.add(node.left);
                }
                if (node.right != null) {
                    q.add(node.right);
                }
            }
            
           res.add(list); 
        }
        return res;
    }
}

BFS: level order

BFS: shortest path

also a grid search

DFS: grid struction: island

1. DFS basic structure

void traverse(TreeNode root) {
   // base case
   if (root == null) {
       return;
   }
   // 
   traverse(root.left);
   traverse(root.right);
}

grid (r, c) , its neigbor: (r -1, c), (r + 1, c), (r, c - 1), (r, c + 1)

2. DFS grid basic structure

void dfs(int[][] grid, int r, int c) {
   // base case, (r, c)exceed the board
   if (!inArea(grid, r, c)) {
       return;
   }
   // 
  dfs(grid, r -1, c);
  dfs(grid, r + 1, c);
  dfs(grid, r, c - 1);
  dfs(grid, r, c + 1);
}

boolean inArea(int[][] grid, int r, int c) {
   return 0 <= r && r < grid.length && 
   && 0 <= c && c < grid[0].length;
}

3. record the visited grid

  • 0 –occean
  • 1 –island (unvisited)
  • 2 –island (visited)
 void dfs(int[][] grid, int r, int c) {
    // base case, (r, c)exceed the board
    if (!inArea(grid, r, c)) {
        return;
    }

     if (grid[r][c] != 1) {
        return;
    }

    grid[r][c] = 2
    // 
   dfs(grid, r -1, c);
   dfs(grid, r + 1, c);
   dfs(grid, r, c - 1);
   dfs(grid, r, c + 1);
}

boolean inArea(int[][] grid, int r, int c) {
    return 0 <= r && r < grid.length && 
    && 0 <= c && c < grid[0].length;
}

LeetCode Max Area of Island LeetCode Making A Large Island LeetCode Island Perimeter