标签:
?翻转二叉树
下面我们分别用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