F_G

许多问题需要说清楚就可以&&走永远比跑来的重要

导航

[剑指offer] 二叉搜索树与双向链表

二叉搜索树与双向链表 p168

题目描述:

将二叉搜索树的left和right指针看做双向链表的pre指针和next指针,将二叉搜索树转化为双向链表的格式,并且保持递增的序列

solution:使用中序遍历的方式

递归版本

TreeNode previouse = NULL;

TreeNode head = NULL;

BST2DList(TreeNode root):

  if(root==null) return;

  BST2DList(root.left);

  if(previouse==NULL){//第一个节点,也就是最小的节点

    head = root;

    previouse = root;

  }else{

    previouse.right = root;

    root.left = previouse;

    previouse = root;

  }

  BST2DList(root.right);

二、非递归版本

TreeNode previous = NULL;

TreeNode head = NULL;

BST2DList(TreeNode root):

  Stack<TreeNode> stack = new Stack<TreeNode>();

  TreeNode current = root;

  while(current!=null||!stack.isEmpty()){

    while(current!=null){

      stack.push(current);

      current = current.left;

    }

    current = stack.pop();

     if(previous == NULL){

      previous = head = current;

     }else{

      previous.right = current;

      current.left = previous;

      previous = current;

    }

    current = current.right;

    return head;

  }

posted on 2015-09-04 16:10  F_G  阅读(189)  评论(0编辑  收藏  举报