首页 > 其他 > 详细

LeetCode#226 Invert Binary Tree

时间:2015-09-08 21:45:49      阅读:473      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!