文章最前: 我是Octopus,这个名字来源于我的中文名--章鱼;我热爱编程、热爱算法、热爱开源。所有源码在我的个人github ;这博客是记录我学习的点点滴滴,如果您对 Python、Java、AI、算法有兴趣,可以关注我的动态,一起学习,共同进步。
相关文章:
- LeetCode:55. Jump Game(跳远比赛)
- Leetcode:300. Longest Increasing Subsequence(最大增长序列)
- LeetCode:560. Subarray Sum Equals K(找出数组中连续子串和等于k)
文章目录:
源码github地址:https://github.com/zhangyu345293721/leetcode
题目描述:
给定一个二叉树,将它展开为链表。
例如,给定二叉树;
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
java实现方式1:(利用栈的形式)
/**
* 将二叉树改为链表
*
* @root 根节点
*/
public void flatten(TreeNode root) {
if (root == null) {
return;
}
Deque<TreeNode> stack = new LinkedList<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode currentNode = stack.pop();
if (currentNode.right != null) {
stack.push(currentNode.right);
}
if (currentNode.left != null) {
stack.push(currentNode.left);
}
if (!stack.isEmpty()) {
currentNode.right = stack.peek();
}
// 左子树要为空
currentNode.left = null;
}
}
时间复杂度:O(n)
空间复杂度:O(1)
python实现方式1:
def flatten(self, root: TreeNode) -> None:
'''
转换二叉树
Args:
root: 根节点
Returns:
只有有节点的二叉树
'''
if root == None:
return
stack = []
stack.append(root)
while len(stack) > 0:
current_node = stack.pop()
if current_node.right:
stack.append(current_node.right)
if current_node.left:
stack.append(current_node.left)
if len(stack) > 0:
current_node.right = stack[-1]
current_node.left = None
时间复杂度:O(n)
空间复杂度:O(1)
java实现方式2:递归形式
/**
* 将二叉树改为链表
*
* @root 根节点
*/
public void flatten2(TreeNode root) {
flattenForList(root, null);
}
/**
* 将二叉树遍历成链表
*
* @param root 根节点
* @param current 当前节点
* @return 节点
*/
private TreeNode flattenForList(TreeNode root, TreeNode current) {
if (root == null) {
return current;
}
current = flattenForList(root.right, current);
current = flattenForList(root.left, current);
root.left = null;
root.right = current;
return root;
}
时间复杂度:O(n)
空间复杂度:O(n)
python实现方式2:递归方式
def flatten_for_list(self, root: TreeNode, current_node) -> TreeNode:
'''
循环递归树
Args:
root: 根节点
current_node: 当前节点
Returns:
root
'''
if not root:
return current_node
current_node = self.flatten_for_list(root.right, current_node)
current_node = self.flatten_for_list(root.left, current_node)
root.left = None
root.right = current_node
return root
def flatten2(self, root: TreeNode) -> None:
'''
转换二叉树
Args:
root: 根节点
Returns:
只有有节点的二叉树
'''
self.flatten_for_list(root, None)
时间复杂度:O(n)
空间复杂度:O(n)