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

Flatten Binary Tree to Linked List

时间:2017-06-02 09:55:54      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:oid   lease   .com   link   trace   void   ram   question   www   

Note:

It is easier to use divided conquer. As you can see, the question is just to add right to left‘s last. Here we care more about last then the top because top can always be traced by root. Since the right is the last if it is null, first return right and then check left side. 

/**
 * 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 flatten(TreeNode root) {
        // write your code here
        flattenTree(root);
    }
    
    private TreeNode flattenTree(TreeNode root) {
        if (root == null) {
            return root;
        }
        
        //This problem is looking for the last element
        TreeNode leftLast = flattenTree(root.left);
        TreeNode rightLast = flattenTree(root.right);
        
        if (leftLast != null) {
            leftLast.right = root.right;
            root.right = root.left;
            root.left = null;
        }
        
        if (rightLast != null) {
            return rightLast;
        }
        
        if (leftLast != null) {
            return leftLast;
        }
        
        return root;
    }
}

 

// The traverse version. Please check http://www.jiuzhang.com/solutions/flatten-binary-tree-to-linked-list/

Flatten Binary Tree to Linked List

标签:oid   lease   .com   link   trace   void   ram   question   www   

原文地址:http://www.cnblogs.com/codingEskimo/p/6931577.html

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