首页 > 其他 > 详细

lintcode 容易题:Invert Binary Tree 翻转二叉树

时间:2015-10-18 15:33:47      阅读:653      评论:0      收藏:0      [点我收藏+]

题目:

翻转一棵二叉树

样例
  1         1
 / \       / 2   3  => 3   2
   /         4         4
挑战

递归固然可行,能否写个非递归的?

解题:

递归比较简单,非递归待补充

Java程序:

技术分享
/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root: a TreeNode, the root of the binary tree
     * @return: nothing
     */
    public void invertBinaryTree(TreeNode root) {
        // write your code here
        invertTree(root);
        
    }
    public TreeNode invertTree(TreeNode root){
        if( root ==null){
            return root;
        }
        TreeNode rleft= root.left;
        root.left = invertTree(root.right);
        root.right = invertTree(rleft);
        return root;
    }
}
View Code

总耗时: 994 ms

Python程序:

技术分享
"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""
class Solution:
    # @param root: a TreeNode, the root of the binary tree
    # @return: nothing
    def invertBinaryTree(self, root):
        # write your code here
        self.invertTree(root)
        
    def invertTree(self,root):
        if root == None:
            return root
        rlft = root.left
        root.left = self.invertTree(root.right)
        root.right = self.invertTree(rlft)
        return root 
View Code

总耗时: 118 ms

lintcode 容易题:Invert Binary Tree 翻转二叉树

原文:http://www.cnblogs.com/theskulls/p/4889550.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!