力扣链接https://leetcode.cn/problems/er-cha-sou-suo-shu-yu-shuang-xiang-lian-biao-lcof/description/
解题思路
中序遍历可以得到排序的序列,遍历时维护当前节点和前一个节点,改变左右指针。头节点设为null,遍历开始判断一下然后初始化。尾节点中序遍历时一直更新。
/* // Definition for a Node. class Node { public int val; public Node left; public Node right; public Node() {} public Node(int _val) { val = _val; } public Node(int _val,Node _left,Node _right) { val = _val; left = _left; right = _right; } }; */ class Solution { Node head,end; void dfs(Node root){ if(root==null){ return; } dfs(root.left); if(head==null){ head=root; } else{ root.left=end; end.right=root; } end=root; //作为前继节点 dfs(root.right); } public Node treeToDoublyList(Node root) { if(root==null){ return null; } dfs(root); head.left=end; end.right=head; return head; } }