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

[LeetCode]114 Flatten Binary Tree to Linked List

时间:2015-01-06 18:20:38      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:leetcode

https://oj.leetcode.com/problems/flatten-binary-tree-to-linked-list/

http://blog.csdn.net/linhuanmars/article/details/23717703

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public void flatten(TreeNode root) {
        if (root == null)
            return;
        handle(root);
    }
    
    // Returns flattened tail.
    TreeNode handle(TreeNode node)
    {
        if (node.left == null && node.right == null)
            return node;
            
        TreeNode righttail = null;
        if (node.right != null)
            righttail = handle(node.right);
            
        if (node.left != null)
        {
            TreeNode lefttail = handle(node.left);
            TreeNode right = node.right;
            node.right = node.left;
            node.left = null;
            if (righttail == null)
                righttail = lefttail;
            else
                lefttail.right = right;
        }
        
        return righttail;
    }
}

[LeetCode]114 Flatten Binary Tree to Linked List

标签:leetcode

原文地址:http://7371901.blog.51cto.com/7361901/1599733

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