Leetcode-0226 flipped binary tree

Time:2021-7-1

Title addresshttps://leetcode-cn.com/problems/invert-binary-tree/

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)andinvertTree(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) {
        Queue<TreeNode> queue = new LinkedList<>();
        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/