LeetCode第543题:翻转二叉树

198 阅读1分钟

题干

翻转一棵二叉树。

示例:

输入:

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

输出:

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

解法:深度优先搜索

首先使用二叉树的后序遍历,递归函数的结束条件是root==null时,说明root已经为叶子节点,接着记录当前节点的右子树于左子树,交换位置,返回root即可。

代码实现:

 /**
  * @param {TreeNode} root
  * @return {TreeNode}
  */
 var invertTree = function (root) {
     doswap(root);
     return root
 };
 function doswap(root) {
     if (root == null) return null;
     let anode = doswap(root.left);
     let bnode = doswap(root.right);
     root.left=bnode;
     root.right=anode;
     return root
 }
 ​

\