树的遍历 深度优先 宽度优先

树的遍历分为两种,一种是深度优先遍历,另一种是广度优先遍历。

有如下一个 二叉树
这里写图片描述

广度优先遍历是从根节点开始,沿着树的宽度遍历树的节点。如果所有节点均被访问,则中止。
广度优先遍历 A B D C E F

深度优先遍历是是沿着树的深度遍历树的节点,尽可能深的搜索树的分支
深度优先 A B C D E F


php代码具体实现如下

<?php

// 节点
class Node
{
    public $val = null;
    public $left = null;
    public $right = null;
}

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

$root->val = 1;
$node1->val = 2;
$node2->val = 3;
$node3->val = 4;
$node4->val = 5;
$node5->val = 6;
$node6->val = 7;

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


/*
$root 的结构如下
        1
    2       3
  4   5   6   7
*/

// 广度优先遍历 通过队列来实现(非递归)
function breadth_traverse($root)
{
    $data = [];
    $queue = [];
    // 将根节点入队列
    array_unshift($queue, $root);

    while ($queue) {
        $node = array_pop($queue);
        array_push($data, $node->val);

        if ($node->left) { // 左节点入队列
            array_unshift($queue, $node->left);
        }
        if ($node->right) { // 右节点入队列
            array_unshift($queue, $node->right);
        }
    }

    return $data;
}

// 深度优先遍历 递归实现
function depth_traverse($root)
{
    if (!$root->left && !$root->right) {
        return [$root->val];
    }
    // merge (当前节点,子节点,右节点)
    return array_merge([$root->val], depth_traverse($root->left), depth_traverse($root->right));
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是图的深度优先遍历宽度优先遍历的介绍: 深度优先遍历(DFS): 深度优先遍历是一种用于遍历搜索或图的算法。在这种搜索方法中,从根结点开始,尽可能深地搜索每个分支,直到到达最深的结点,然后回溯到前一个结点,继续搜索另一个分支,直到所有结点都被访问为止。深度优先遍历使用栈来实现,因此也称为“栈搜索”。 以下是深度优先遍历的Python代码示例: ```python # Python3 program to print DFS traversal # from a given given graph from collections import defaultdict # This class represents a directed graph using # adjacency list representation class Graph: # Constructor def __init__(self): # default dictionary to store graph self.graph = defaultdict(list) # function to add an edge to graph def addEdge(self, u, v): self.graph[u].append(v) # A function used by DFS def DFSUtil(self, v, visited): # Mark the current node as visited # and print it visited.add(v) print(v, end=' ') # Recur for all the vertices # adjacent to this vertex for neighbour in self.graph[v]: if neighbour not in visited: self.DFSUtil(neighbour, visited) # The function to do DFS traversal. It uses # recursive DFSUtil() def DFS(self, v): # Create a set to store visited vertices visited = set() # Call the recursive helper function # to print DFS traversal self.DFSUtil(v, visited) ``` 宽度优先遍历(BFS): 宽度优先遍历是一种用于遍历搜索或图的算法。在这种搜索方法中,从根结点开始,逐层遍历每个结点的所有子结点,直到到达最深的结点。宽度优先遍历使用队列来实现。 以下是宽度优先遍历的Python代码示例: ```python # Python3 program to print BFS traversal # from a given source vertex. BFS(int s) # traverses vertices reachable from s. from collections import defaultdict # This class represents a directed graph # using adjacency list representation class Graph: # Constructor def __init__(self): # default dictionary to store graph self.graph = defaultdict(list) # function to add an edge to graph def addEdge(self, u, v): self.graph[u].append(v) # Function to print a BFS of graph def BFS(self, s): # Mark all the vertices as not visited visited = [False] * (max(self.graph) + 1) # Create a queue for BFS queue = [] # Mark the source node as # visited and enqueue it queue.append(s) visited[s] = True while queue: # Dequeue a vertex from # queue and print it s = queue.pop(0) print(s, end=" ") # Get all adjacent vertices of the # dequeued vertex s. If a adjacent # has not been visited, then mark it # visited and enqueue it for i in self.graph[s]: if visited[i] == False: queue.append(i) visited[i] = True ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值