topic
Thinking
- First is a binary tree may be determined preorder
- To define a prenode, a curnode, a headnode
- First, find the leftmost leaf node 4, will be assigned to him headnode and prenode
- The traversal sequence then, will arrive CURNODE node 6, the connection between the left and CURNODE prenode the prenode set CURNODE, inorder traversal continues, this time will come CURNODE 8, prenode 6, connected to the left and right, then prenode 8 is set to continue traversal. . When the traversal is complete, the entire doubly linked list is finished, the head node for the natural headnode.
Code
/**
*
*/
/***
* @author 18071
* @Date 2019年3月13日
* 功能:二叉搜索树 与双向链表
***/
public class test {
public static void main(String args[]) {
TreeNode root =new TreeNode (4);
root.right=new TreeNode (6);
root.left=new TreeNode (2);
root.left.left=new TreeNode (1);
root.left.right=new TreeNode(3);
Solution s =new Solution();
TreeNode realhead=null;
s.Sys(root);
}
}
//本题重要的一点是不能创建出新的节点
//中序遍历
//
class Solution{
TreeNode realhead=null;
TreeNode prehead=null;
public void Sys(TreeNode root) {
convert(root);
while(realhead!=null) {
System.out.println(realhead.val);
realhead=realhead.right;
}
}
public void convert(TreeNode root) {
if(root==null) {
return ;
}
convert(root.left);
//if()
if(realhead==null) {
realhead=root;
prehead=root;
System.out.println("双线链表头结点已找到 ::"+realhead.val);
}
else {
System.out.println("当前节点为"+ root.val);
System.out.println("当前prehead 节点为"+ prehead.val);
//左右连接
root.left=prehead;
prehead.right=root;
//左右连接
prehead = root ;
}
convert(root.right);
}
}
class TreeNode{
TreeNode left;
TreeNode right;
int val;
TreeNode(int val){
this.val=val;
}
}