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

17.13 BST转换成双向链表。

时间:2014-08-24 12:51:12      阅读:267      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   div   log   new   sp   

 

思路:递归执行,子函数需要返回子链表的head和tail,所以借助内部类NodePair来实现。

 

/**
 * 

         4
       /         2     5
     / \         1   3     6
   /
  0
  
  0<=>1<=>2<=>3<=>4<=>5<=>6
  
 *
 */
public class Solution {

    public TreeNode BSTtoDLL(TreeNode root) {
        TreeNode res = BSTtoList(root).head;
        return res;
    }

    private NodePair BSTtoList(TreeNode root) {
        if (root == null)
            return null;
        NodePair leftPair = BSTtoList(root.left);
        NodePair rightPair = BSTtoList(root.right);
        if (leftPair != null) {
            leftPair.tail.right = root;
            root.left = leftPair.tail;
        }

        if (rightPair != null) {
            root.right = rightPair.head;
            rightPair.head.left = root;
        }
        TreeNode newHead = root;
        TreeNode newTail = root;
        if (leftPair != null) {
            newHead = leftPair.head;
        }
        if (rightPair != null) {
            newTail = rightPair.tail;
        }

        return new NodePair(newHead, newTail);

    }

    private static class NodePair {
        TreeNode head;
        TreeNode tail;

        public NodePair(TreeNode head, TreeNode tail) {
            this.head = head;
            this.tail = tail;
        }

    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(4);
        root.left = new TreeNode(2);
        root.right = new TreeNode(5);
        root.left.left = new TreeNode(1);
        root.left.right = new TreeNode(3);
        root.left.left.left = new TreeNode(0);
        root.right.right = new TreeNode(6);

        System.out.println(new Solution().BSTtoDLL(root));

    }
}

 

17.13 BST转换成双向链表。

标签:style   blog   color   io   ar   div   log   new   sp   

原文地址:http://www.cnblogs.com/jdflyfly/p/3932647.html

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