199. 二叉树的右视图
层次遍历二叉树(BFS)
class Solution {
function rightSideView($root) {
$ans = [];
if ( $root == null ) {
return $ans;
}
$queue = [];
array_push($queue, $root);
while ( count($queue) > 0 ) {
$len = count($queue);
for ($i = 0; $i < $len; $i++) {
$node = array_shift($queue);
if ( $i+1 == $len ) {
array_push($ans, $node->val);
}
if ( $node->left ) {
array_push($queue, $node->left);
}
if ( $node->right ) {
array_push($queue, $node->right);
}
}
}
return $ans;
}
}
深度遍历二叉树(DFS)
class Solution {
function rightSideView($root) {
$ans = [];
if ( $root == null ) {
return $ans;
}
$this->dfs($root, 0, $ans);
return $ans;
}
function dfs($root, $depth, &$ans) {
if ( $root == null ) {
return;
}
if ($depth === count($ans) ) {
array_push( $ans, $root->val );
}
$this->dfs( $root->right, $depth+1, $ans );
$this->dfs( $root->left, $depth+1, $ans );
}
}
|