首页 > 其他 > 详细

17.13 BST转换成双向链表。

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

 

思路:递归执行,子函数需要返回子链表的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转换成双向链表。

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

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