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

Flatten Binary Tree to Linked List ——LeetCode

时间:2015-04-13 22:34:41      阅读:141      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!