[LeetCode]114 Flatten Binary Tree to Linked List

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)