chencl1986 / Blog

Welcome to lee's blog.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

LeetCode题解:226. 翻转二叉树,递归,JavaScript,详细注释

chencl1986 opened this issue · comments

原题链接:https://leetcode-cn.com/problems/invert-binary-tree/

解题思路:

  1. 使用递归首先要思考,当前递归函数运行的是第n次递归,那么当前要做哪些处理。
  2. 先考虑的是,假设此时遍历到了最后一个节点为null,要给递归设置终止条件。
  3. 在当前递归,将子节点互换,并使用新的子节点进行下一层递归。
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
function recursion(node) {
  // 如果当前节点不存在,则退出递归
  if (!node) {
    return;
  }

  // 将子节点互换
  const temp = node.left;
  node.left = node.right;
  node.right = temp;

  // 遍历互换后的子节点
  recursion(node.left);
  recursion(node.right);
}
/**
 * @param {TreeNode} root
 * @return {TreeNode}
 */
var invertTree = function (root) {
  // 递归遍历节点,并进行翻转
  recursion(root);
  return root;
};