[二叉树]!226. Invert Binary Tree

2017-10-25  本文已影响0人  Reflection_

题目: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;
    }
}
上一篇下一篇

猜你喜欢

热点阅读