码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] 114. Flatten Binary Tree to Linked List

时间:2020-03-17 08:43:05      阅读:38      评论:0      收藏:0      [点我收藏+]

标签:===   指针   param   current   展开   先序遍历   var   root   tco   

将二叉树展开成链表。题意是给一个二叉树,请原地展开成一个链表。例子,

For example, given the following tree:

    1
   /   2   5
 / \   3   4   6

The 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 }

 

JavaScript实现

 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

标签:===   指针   param   current   展开   先序遍历   var   root   tco   

原文地址:https://www.cnblogs.com/aaronliu1991/p/12508322.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!