上一次基本了解了下BFS,这次又找了个基本的DFS题目来试试水,DFS举个例子来说就是 一种从树的最左端开始一直搜索到最底端,然后回到原端再搜索另一个位置到最底端,也就是称为深度搜索的DFS--depth first search,话不多说,直接上题了解: Description:某石油勘探公司正在按计划勘探地下油田资源,工作在一片长方形的地域中.他们首先将该地域划分为许多小正方形区域,然后使用探测设备分别探测每一块小正方形区域内是否有油.若在一块小正方形区域中探测到有油,则标记为’@’,否则标…
Given a binary tree struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode *next; } Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. Initially, al…
Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. Hide Tags Tree Depth-first Search …
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. Hide Tags Depth-first Search Linked List 这题是将链表变成二叉树,比较麻烦的遍历过程,因为链表的限制,所以深度搜索的顺序恰巧是链表的顺序,通过设置好递归函数的参数,可以在深度搜索时候便可以遍历了. TreeNode * he…
Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Hide Tags Tree Depth-first Search 简单的深度搜索 #include <iostream> using namespace std; /*…
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. An example is the root-to-leaf path 1->2->3 which represents the number 123. Find the total sum of all root-to-leaf numbers. For example, 1 / \ 2 3…
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. For example:Given the below binary tree and sum = 22, 5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1 return [ [5,4,11,2], [5,8,4,5] ] Hide Tags Tree Depth…
bool DFS(Node n, int d){ if (d == 4){//路径长度为返回true,表示此次搜索有解 return true; } for (Node nextNode in n){//遍历跟节点n相邻的节点nextNode, if (!visit[nextNode]){//未访问过的节点才能继续搜索 //例如搜索到V1了,那么V1要设置成已访问 visit[nextNode] = true; //接下来要从V1开始继续访问了,路径长度当然要加 if (DFS(nextNode…
Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be us…