上次编辑到这里,代码来自缓存 点击恢复默认模板
/*
// Definition for a Node.
class Node {
public:
int val;
Node* left;
Node* right;
Node() {}
Node(int _val) {
val = _val;
left = NULL;
right = NULL;
}
Node(int _val, Node* _left, Node* _right) {
val = _val;
left = _left;
right = _right;
}
};
*/
class Solution {
public:
Node* treeToDoublyList(Node* root) {
}
};
java 解法, 执行用时: 0 ms, 内存消耗: 41 MB, 提交时间: 2022-11-13 12:46:15
/*
// 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 {
// 1. 中序,递归,来自解题大佬
Node pre, head;
public Node treeToDoublyList(Node root) {
// 边界值
if(root == null) return null;
dfs(root);
// 题目要求头尾连接
head.left = pre;
pre.right = head;
// 返回头节点
return head;
}
void dfs(Node cur) {
// 递归结束条件
if(cur == null) return;
dfs(cur.left);
// 如果pre为空,就说明是第一个节点,头结点,然后用head保存头结点,用于之后的返回
if (pre == null) head = cur;
// 如果不为空,那就说明是中间的节点。并且pre保存的是上一个节点,
// 让上一个节点的右指针指向当前节点
else if (pre != null) pre.right = cur;
// 再让当前节点的左指针指向父节点,也就连成了双向链表
cur.left = pre;
// 保存当前节点,用于下层递归创建
pre = cur;
dfs(cur.right);
}
}
python3 解法, 执行用时: 44 ms, 内存消耗: 16.2 MB, 提交时间: 2022-11-13 12:45:02
"""
# Definition for a Node.
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
"""
class Solution:
def treeToDoublyList(self, root: 'Node') -> 'Node':
def dfs(cur):
if not cur: return
dfs(cur.left) # 递归左子树
if self.pre: # 修改节点引用
self.pre.right, cur.left = cur, self.pre
else: # 记录头节点
self.head = cur
self.pre = cur # 保存 cur
dfs(cur.right) # 递归右子树
if not root: return
self.pre = None
dfs(root)
self.head.left, self.pre.right = self.pre, self.head
return self.head