码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode#226 Invert Binary Tree

时间:2015-09-08 21:49:05      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:

Invert Binary Tree

?翻转二叉树

下面我们分别用java和python实现两种解决方案(两种解决方案可以完全用java或python实现:

?

方案一:(java)

/**

?* 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 root;

? ? ? ??

? ? ? ? Queue<TreeNode> lineNodes = new LinkedList<TreeNode>();

? ? ? ? lineNodes.add(root);

? ? ? ??

? ? ? ? TreeNode current, tmp;

? ? ? ? while(!lineNodes.isEmpty()){

? ? ? ? ? ? current = lineNodes.remove();

? ? ? ? ? ??

? ? ? ? ? ? tmp = current.left;

? ? ? ? ? ? current.left = current.right;

? ? ? ? ? ? current.right = tmp;

? ? ? ? ? ??

? ? ? ? ? ? if(current.left != null){

? ? ? ? ? ? ? ? lineNodes.add(current.left);

? ? ? ? ? ? }

? ? ? ? ? ? if(current.right != null){

? ? ? ? ? ? ? ? lineNodes.add(current.right);

? ? ? ? ? ? }

? ? ? ? }

? ? ? ? return root;

? ? }

}

方案二:(python)

# Definition for a binary tree node.

# class TreeNode(object):

# ? ? def __init__(self, x):

# ? ? ? ? self.val = x

# ? ? ? ? self.left = None

# ? ? ? ? self.right = None

?

class Solution(object):

? ? def invertTree(self, root):

? ? ? ? """

? ? ? ? :type root: TreeNode

? ? ? ? :rtype: TreeNode

? ? ? ? """

? ? ? ? if root==None:

? ? ? ? ? ? return root

? ? ? ? tmp = root.left

? ? ? ? root.left = self.invertTree(root.right)

? ? ? ? root.right = self.invertTree(tmp)

? ? ? ? return root

LeetCode#226 Invert Binary Tree

标签:

原文地址:http://www.cnblogs.com/kevinCK/p/4792886.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!