首页 > 其他 > 详细

8.7 114 Flatten Binary Tree to Linked List

时间:2015-08-08 01:07:33      阅读:250      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!