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

lintcode-easy-Flatten Binary Tree to Linked List

时间:2016-02-24 19:20:04      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:

Flatten a binary tree to a fake "linked list" in pre-order traversal.

Here we use the right pointer in TreeNode as the nextpointer in ListNode.

Example
              1
                    1          2
    / \             2   5    =>    3
  / \   \           3   4   6          4
                                           5
                                               6
Note

Don‘t forget to mark the left child of each node to null. Or you will get Time Limit Exceeded or Memory Limit Exceeded.

Challenge

Do it in-place without any extra memory.

 

递归一下,注意如果左子树为null直接flatten右子树然后返回,否则超时

/**
 * 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
        if(root == null)
            return;
            
        if(root.left == null && root.right == null)
            return;
        
        if(root.left != null){
            flatten(root.left);
        }
        
        if(root.right != null){
            flatten(root.right);
        }
        
        TreeNode temp = root.right;
        
        if(root.left != null){
            root.right = root.left;
            root.left = null;
            TreeNode p = root;
            while(p.right != null)
                p = p.right;
        
        p.right = temp; 
        }
        
        
        
        return;
    }
}

 

lintcode-easy-Flatten Binary Tree to Linked List

标签:

原文地址:http://www.cnblogs.com/goblinengineer/p/5213925.html

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