-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflattenBinaryTreeToLinkedList.php
More file actions
63 lines (50 loc) · 1.36 KB
/
flattenBinaryTreeToLinkedList.php
File metadata and controls
63 lines (50 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<?php
class TreeNode {
public $val = null;
public $left = null;
public $right = null;
function __construct($val = 0, $left = null, $right = null) {
$this->val = $val;
$this->left = $left;
$this->right = $right;
}
}
class Solution
{
public $tail;
/**
* 给你二叉树的根结点 root ,请你将它展开为一个单链表:
*
* 展开后的单链表应该同样使用 TreeNode ,其中 right 子指针指向链表中下一个结点,而左子指针始终为 null 。
* 展开后的单链表应该与二叉树 先序遍历 顺序相同。
* root = [1,2,5,3,4,null,6] =》 [1,null,2,null,3,null,4,null,5,null,6]
* @param TreeNode $root
* @return NULL
*/
function flatten($root)
{
if($root === null){
return null;
}
$dummyHead = new TreeNode();
$this->tail = $dummyHead;
//前序遍历展开
$this->preorder($root);
return $dummyHead;
}
function preorder($root)
{
if($root === null){
return;
}
//左子树
$left = $root->left;
//右子树
$right = $root->right;
$this->tail->right = $root;
$this->tail->left = null;
$this->tail = $root;
$this->preorder($left);
$this->preorder($right);
}
}