LeetCode-226. Invert Binary Tree

来源:互联网 发布:asp.net管理系统源码 编辑:程序博客网 时间:2024/05/12 12:44

226. Invert Binary Tree

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.

就是一个翻转二叉树,递归的程序自己还是写不出来,感觉一片浆糊,o(╥﹏╥)o

非递归:

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */class Solution {    public TreeNode invertTree(TreeNode root) {        if (root == null) return null;        Queue<TreeNode> queue = new LinkedList<TreeNode>();        queue.add(root);        while (!queue.isEmpty()) {            TreeNode current = queue.poll();            TreeNode temp = current.left;            current.left = current.right;            current.right = temp;            if (current.left != null) queue.add(current.left);            if (current.right != null) queue.add(current.right);        }        return root;    }}


递归:

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



原创粉丝点击