-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path145.二叉树的后序遍历.php
73 lines (66 loc) · 1.39 KB
/
145.二叉树的后序遍历.php
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
64
65
66
67
68
69
70
71
72
73
<?php
/*
* @lc app=leetcode.cn id=145 lang=php
*
* [145] 二叉树的后序遍历
*
* https://leetcode-cn.com/problems/binary-tree-postorder-traversal/description/
*
* algorithms
* Easy (74.58%)
* Likes: 609
* Dislikes: 0
* Total Accepted: 243.9K
* Total Submissions: 327K
* Testcase Example: '[1,null,2,3]'
*
* 给定一个二叉树,返回它的 后序 遍历。
*
* 示例:
*
* 输入: [1,null,2,3]
* 1
* \
* 2
* /
* 3
*
* 输出: [3,2,1]
*
* 进阶: 递归算法很简单,你可以通过迭代算法完成吗?
*
*/
// @lc code=start
/**
* Definition for a binary tree node.
* 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
{
/**
* @param TreeNode $root
* @return int[]
*/
public function postorderTraversal($root)
{
$orders = [];
if ($root->left) {
$orders = array_merge($orders, $this->postorderTraversal($root->left));
}
if ($root->right) {
$orders = array_merge($orders, $this->postorderTraversal($root->right));
}
$orders[] = $root->val;
return $orders;
}
}
// @lc code=end