来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-preorder-traversal/
著作权归领扣网络所有。
给你二叉树的根节点 root ,返回它节点值的 前序 遍历。
迭代法1-一层循环
/**
* 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 Integer[]
*/
function preorderTraversal($root) {
$res = [];
if ( $root == null ) {
return $res;
}
$stack = [];
$top = 0;
$stack[$top++] = $root;
while ($top) {
$root = $stack[--$top];
$res[] = $root->val;
$root->right && $stack[$top++] = $root->right;
$root->left && $stack[$top++] = $root->left;
}
return $res;
}
}
迭代法2-两层循环
/**
* 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 Integer[]
*/
function preorderTraversal($root) {
$res = [];
$stack = [];
$top = 0;
while ($top || $root) {
while($root) {
$res[] = $root->val;
$stack[$top++] = $root;
$root = $root->left;
}
$root = $stack[--$top];
$root = $root->right;
}
return $res;
}
}
递归
/**
* 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 Integer[]
*/
function preorderTraversal($root) {
$res = [];
$this->dfs($root, $res);
return $res;
}
function dfs($root, &$res) {
if ($root != null) {
$res[] = $root->val;
$this->dfs($root->left, $res);
$this->dfs($root->right, $res);
}
}
}
Morris 遍历
/**
* 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 Integer[]
*/
function preorderTraversal($root) {
$res = [];
$p1 = $root;
$p2 = null;
while ($p1) {
if ($p1->left) {
$p2 = $p1->left;
while ($p2->right && $p2->right != $p1) {
$p2 = $p2->right;
}
if ( $p2->right == null ) {
$res[] = $p1->val;
$p2->right = $p1;
$p1 = $p1->left;
continue;
} else {
$p2->right = null;
}
} else {
$res[] = $p1->val;
}
$p1 = $p1->right;
}
return $res;
}
}