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

8.7 114 Flatten Binary Tree to Linked List

时间:2015-08-08 01:10:06      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:

Question:

Given a binary tree, flatten it to a linked list in-place.

For example,
Given

         1
        /        2   5
      / \        3   4   6

 

The flattened tree should look like:

   1
         2
             3
                 4
                     5
                         6

Method: put root.left to its right, and connect root.right to its original left.right(if root.left.right == null then connect root.right to root.left)
    public void flatten(TreeNode root) {
        while(root != null) {
            if(root.left != null) {
                TreeNode lr = root.left.right;
                while(lr != null && lr.right != null)
                    lr = lr.right;
                if(lr == null) // if left has no right nodes then use root.left to connect root.right.
                    lr = root.left;
                TreeNode temp = root.right;
                root.right = root.left;
                lr.right = temp;
                root.left = null;
            }
            root = root.right;
        }
    }

 

8.7 114 Flatten Binary Tree to Linked List

标签:

原文地址:http://www.cnblogs.com/michael-du/p/4712275.html

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