美文网首页
[二叉树]!226. Invert Binary Tree

[二叉树]!226. Invert Binary Tree

作者: Reflection_ | 来源:发表于2017-10-25 16:03 被阅读0次

    题目:226. Invert Binary Tree

    经典考题。水平翻转二叉树。

    这个题有个额外的小故事:
    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.

    Invert a binary tree.

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

    DFS遍历。每一个root下的左右对换。

    class Solution {
        public TreeNode invertTree(TreeNode root) {
            if(root == null) return null;
    
            TreeNode newNode = root.left;
            root.left = root.right;
            root.right = newNode;
    
            invertTree(root.left);
            invertTree(root.right);
            
            return root;
        }
    }
    

    相关文章

      网友评论

          本文标题:[二叉树]!226. Invert Binary Tree

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