2015-06-12 五-翻转二叉树

来源:互联网 发布:手游英雄杀十连抽数据 编辑:程序博客网 时间:2024/06/13 20:57

Friday, June 12, 2015 10:21 PM

leetcode——226 Invert Binary Tree(翻转二叉树,会做就能进谷歌哦~~)

Invert Binary Tree | LeetCode OJ
https://leetcode.com/problems/invert-binary-tree/

Invert Binary Tree Total Accepted: 1332 Total Submissions: 3716 My Submissions Question Solution Invert a binary tree.     4   /   \  2     7 / \   / \1   3 6   9to     4   /   \  7     2 / \   / \9   6 3   1Trivia: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.

解题思路:
直接获取根节点的左右节点,然后进行交换即可。方法一直接进行交换,方法二使用二叉树层次遍历,话不多说直接上代码。

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public TreeNode invertTree(TreeNode root) {       if (root == null) {            return null;        }        TreeNode t = new TreeNode(root.val);        t.right = invertTree(root.left);        t.left = invertTree(root.right);        return t;    }}

更多
leetcode——226 Invert Binary Tree(翻转二叉树,会做就能进谷歌哦~~) - zzc8265020的博客 - 博客频道 - CSDN.NET
http://blog.csdn.net/zzc8265020/article/details/46473757

0 0
原创粉丝点击