美文网首页
226. Invert Binary Tree

226. Invert Binary Tree

作者: caisense | 来源:发表于2018-01-26 22:36 被阅读0次

    Invert a binary tree.

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

    to

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

    Trivia:
    This problem was inspired by this original tweet by Max Howell:

    Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off.

    思路:也不知道怎么想出来的,原本觉得翻转二叉树应该用中序遍历(左中右),对应新树变为右中左即可,然而发现中序的话根节点无法正确建立,应该先建立根,再处理左右子树(前序).
    于是算法思想为:前序递归遍历原树,然后新树(根为root2)的右子树用原树的左子树建立,新树的左子树用原树的右子树建立,如此递归.

    TreeNode* invertTree(TreeNode* root) {
        if (!root) return NULL;
        TreeNode* root2 = new TreeNode(root->val);
        root2->right = invertTree(root->left);
        root2->left = invertTree(root->right);
        return root2;
    }
    

    相关文章

      网友评论

          本文标题:226. Invert Binary Tree

          本文链接:https://www.haomeiwen.com/subject/cocgaxtx.html