# Leetcode-0226 flipped binary tree

Time：2021-7-1

#### 1. Recursion

Time complexity O (n) space complexity O (n)
The idea of recursion is to find the termination condition of recursion. The termination condition of recursion can only end recursion if the current node is null. Or we can think about it from another perspective. If this node is not null, it may have child nodes. In this case, we can continue to recurse downward.
Second, we must understand the process of recursion. The recursion of this topic is mainly to flip the left and right subtrees of node. The inverttree function is to find the node with root as the root, flip the whole tree, and return the flipped result. With this understanding, we can understand the code in the same way` invertTree(root.left)`and`invertTree(root.right)`

``````var invertTree = function(root) {
if (root === null) {
return null
}
const left = invertTree(root.left)
const right = invertTree(root.right)
root.left = right
root.right = left
return root
};``````

#### 2. Breadth first traversal (BFS)

Time complexity O (n) space complexity O (n)
Because we need to exchange the left and right subtrees of each node in the binary tree, we need to access each node of the binary tree. Obviously, each node needs to be accessed, but it has nothing to do with the order. BFS and DFS can be used.

``````class Solution {
// BFS
public TreeNode invertTree(TreeNode root) {
if (root == null)
return null;
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
TreeNode tmp = node.left;
node.left = node.right;
node.right = tmp;

if (node.left != null)
queue.offer(node.left);
if (node.right != null)
queue.offer(node.right);
}
return root;
}
}``````

#### 3. Depth first traversal (DFS)

``````var invertTree = function(root) {
if (root === null) {
return root
}
const stack = []
stack.push(root)
while (stack.length) {
const node = stack.pop()
let tmp = node.left
node.left = node.right
node.right = tmp
node.left && stack.push(node.left)
node.right && stack.push(node.right)
}
return root
};``````

For more questions about leetcode and data structure, please pay attention to my GitHubhttps://github.com/GuoLizhi/algorithm/

## The selector returned by ngrx store createselector performs one-step debugging of fetching logic

Test source code: import { Component } from ‘@angular/core’; import { createSelector } from ‘@ngrx/store’; export interface State { counter1: number; counter2: number; } export const selectCounter1 = (state: State) => state.counter1; export const selectCounter2 = (state: State) => state.counter2; export const selectTotal = createSelector( selectCounter1, selectCounter2, (counter1, counter2) => counter1 + counter2 ); // […]