首页 > 其他 > 详细

Flatten Binary Tree to Linked List ——LeetCode

时间:2015-04-13 22:33:10      阅读:231      评论:0      收藏:0      [点我收藏+]

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

 

题目大意:给一个二叉树,将它转为一个list,转换后的序列应该是先序遍历,list由这棵树的右孩子表示。

解题思路:递归的处理左子树,然后处理右子树,将左孩子的右孩子置为当前节点的右孩子,然后将当前节点的右孩子置为左孩子。

    public void flatten(TreeNode root) {
        doFlat(root);
    }

    private void doFlat(TreeNode node) {
        if (node == null) {
            return;
        }

        doFlat(node.left);
        if (node.left!=null) {
            TreeNode tmp = node.left;
            while(tmp.right!=null){
                tmp=tmp.right;
            }
            tmp.right = node.right;
            node.right = node.left;
            node.left = null;
        }
        doFlat(node.right);
    }

 

Flatten Binary Tree to Linked List ——LeetCode

原文:http://www.cnblogs.com/aboutblank/p/4423216.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!