【LeetCode】剑指 Offer 36. 二叉搜索树与双向链表
文章目录
package offer;
//定义节点
class Node{
int value;
Node left;
Node right;
public Node(int value){
this.value = value;
}
public Node(int value, Node left, Node right){
this.value = value;
this.left = left;
this.right = right;
}
@Override
public String toString() {
return "Node{" +
"value=" + value +
'}';
}
}
public class Solution36 {
public static void main(String[] args) {
Node node1 = new Node(4);
Node node2 = new Node(2);
Node node3 = new Node(5);
Node node4 = new Node(1);
Node node5 = new Node(3);
node1.left = node2;
node1.right = node3;
node2.left = node4;
node2.right = node5;
Solution36 solution = new Solution36();
System.out.println(solution.method(node1));
}
Node pre;
Node head;
private Node method(Node root){
if(root == null) return null;
dfs(root);
head.left = pre;
pre.right = head;
return head;
}
private void dfs(Node cur){
if(cur == null) return;
dfs(cur.left);
if(pre != null) pre.right = cur;
else head = cur;
cur.left = pre;
pre = cur;
dfs(cur.right);
}
}
//时间复杂度为 O(n)
//空间复杂度为 O(n)