翻转一棵二叉树。
示例:
输入:

  1. 4
  2. / \
  3. 2 7
  4. / \ / \
  5. 1 3 6 9

输出:

  1. 4
  2. / \
  3. 7 2
  4. / \ / \
  5. 9 6 3 1

递归法实现

  1. /**
  2. * @param {TreeNode} root
  3. * @return {TreeNode}
  4. */
  5. const invertTree = function(root) {
  6. // 定义递归边界
  7. if(!root) {
  8. return root;
  9. }
  10. // 递归交换右孩子的子结点
  11. let right = invertTree(root.right);
  12. // 递归交换左孩子的子结点
  13. let left = invertTree(root.left);
  14. // 交换当前遍历到的两个左右孩子结点
  15. root.left = right;
  16. root.right = left;
  17. return root;
  18. };

迭代法实现

  1. var invertTree = function(root) {
  2. if(!root) return null;
  3. let stack = [];
  4. stack.push(root)
  5. while(stack.length) {
  6. let cur = stack.pop();
  7. if(cur.left) stack.push(cur.left);
  8. if(cur.right) stack.push(cur.right);
  9. // 翻转节点
  10. let q = cur.left;
  11. cur.left = cur.right;
  12. cur.right = q;
  13. }
  14. return root;
  15. };