新手学习算法----二叉树(将一个二叉查找树按照中序遍历转换成双向链表)
题目:将一个二叉查找树按照中序遍历转换成双向链表。
给定一个二叉查找树:
4
/ \
2 5
/ \
1 3
返回 1<->2<->3<->4<->5
。
思路:如果对于当前节点,把右子树转换成双向链表,然后把左子树转换成双向链表,转换的时候我们都标记了链表的头节点和尾节点,那么只需要将当前节点和左子树的尾部相连,和右子树的头部相连即可。
Java代码:这个是借鉴九章里面的解题法。但是对于左右子树转换成二叉树也不是很理解,还待需要继续分析。
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } * Definition for Doubly-ListNode. * public class DoublyListNode { * int val; * DoublyListNode next, prev; * DoublyListNode(int val) { * this.val = val; * this.next = this.prev = null; * } * } */ class ResultType { DoublyListNode first, last; public ResultType(DoublyListNode first, DoublyListNode last) { this.first = first; this.last = last; } } public class Solution { /** * @param root: The root of tree * @return: the head of doubly list node */ public DoublyListNode bstToDoublyList(TreeNode root) { if (root == null) { return null; } ResultType result = helper(root); return result.first; } public ResultType helper(TreeNode root) { if (root == null) { return null; } ResultType left = helper(root.left); ResultType right = helper(root.right); DoublyListNode node = new DoublyListNode(root.val); ResultType result = new ResultType(null, null); if (left == null) { result.first = node; } else { result.first = left.first;//????? left.last.next = node; node.prev = left.last; } if (right == null) { result.last = node; } else { result.last = right.last;//????? right.first.prev = node; node.next = right.first; } return result; } }