[LeetCode] 114. Flatten Binary Tree to Linked List
Posted aaronliu1991
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 114. Flatten Binary Tree to Linked List相关的知识,希望对你有一定的参考价值。
将二叉树展开成链表。题意是给一个二叉树,请原地展开成一个链表。例子,
For example, given the following tree:
1 / 2 5 / 3 4 6The flattened tree should look like:
1 2 3 4 5 6
这里原地的意思应该是单纯地改变每个node的指针指向的节点,而不是不允许用到额外空间。因为比如用递归做,是不可能没有额外的空间复杂度的。这里我给出的是迭代的做法,照着例子看来,最后的输出是按照先序遍历的顺序来的。所以用先序遍历先得到二叉树所有节点的顺序,然后遍历节点的时候做如下循环
把当前节点的左指针置为NULL
head节点的右指针指向当前节点
head节点往右走
时间O(n)
空间O(n)
Java实现
1 class Solution { 2 public void flatten(TreeNode root) { 3 if (root == null) { 4 return; 5 } 6 LinkedList<TreeNode> res = new LinkedList<>(); 7 //前序遍历整棵二叉树 8 dfs(root, res); 9 TreeNode head = res.removeFirst(); 10 head.left = null; 11 //遍历链表,将链表中的TreeNode节点前后串联起来 12 while (res.size() > 0) { 13 TreeNode tmp = res.removeFirst(); 14 tmp.left = null; 15 head.right = tmp; 16 head = head.right; 17 } 18 } 19 20 //前序遍历整棵二叉树,并将遍历的结果放到数组中 21 private void dfs(TreeNode root, List<TreeNode> res) { 22 if (root == null) { 23 return; 24 } 25 res.add(root); 26 dfs(root.left, res); 27 dfs(root.right, res); 28 } 29 }
1 /** 2 * @param {TreeNode} root 3 * @return {void} Do not return anything, modify root in-place instead. 4 */ 5 var flatten = function (root) { 6 if (!root || root.length === 0) return; 7 let nodes = [root]; 8 let current; 9 while (nodes.length > 0) { 10 let node = nodes.pop(); 11 if (node.right) nodes.push(node.right); 12 if (node.left) nodes.push(node.left); 13 node.right = null; 14 node.left = null; 15 if (!current) { 16 current = node; 17 } else { 18 current.right = node; 19 current = node; 20 } 21 } 22 return root; 23 };
以上是关于[LeetCode] 114. Flatten Binary Tree to Linked List的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 114. Flatten Binary Tree to Linked List
leetcode--114. Flatten Binary Tree to Linked List
LeetCode 114. Flatten Binary Tree to Linked List
Leetcode 114, Flatten Binary Tree to Linked List