二叉树深度优先与广度优先遍历

来源:互联网 发布:淘宝无线端店铺装修 编辑:程序博客网 时间:2024/06/18 07:08
<?php
class Node{
    public $data = null;
    public $left = null;
    public $right = null;
}


function breadth_first_traverse($btree){
    $traverse_data = array();
    $queue = array();
    array_unshift($queue, $btree);//根节点插入数组中
    
    while(!empty($queue)){
        $cnode = array_pop($queue);
        $traverse_data[] = $cnode->data;
        
        if($cnode->left != null){
            array_unshift($queue, $cnode->left);
        }
        if($cnode->right != null){
            array_unshift($queue, $cnode->right);
        }
    }
    return $traverse_data;
    
}




function depth_first_traverse($btree){
    $traverse_data = array();
    $stack = array();
    
    array_push($stack, $btree);
    
    while(!empty($stack)){
        $cnode = array_pop($stack);
        $traverse_data[] = $cnode->data;
        
        if($cnode->right != null){
            array_push($stack, $cnode->right);
        }
        if($cnode->left != null){
            array_push($stack, $cnode->left);
        }
    }
    
    return $traverse_data;
    
}


$root = new Node();
$node1 = new Node();
$node2 = new Node();
$node3 = new Node();
$node4 = new Node();


$root->data = 1;
$node1->data = 2;
$node2->data = 3;
$node3->data = 4;
$node4->data = 5;


$root->left = $node1;
$root->right = $node2;
$node1->left = $node3;
$node1->right = $node4;


$traverse = breadth_first_traverse($root);
print_r($traverse);
echo "<br>";


$traverse = depth_first_traverse($root);
print_r($traverse);


?>
0 0