import java.util.ArrayDeque; import java.util.Deque; import java.util.LinkedList; import java.util.Queue; public class MyBinTree { private static class TreeNode { char val; //左右子树节点 TreeNode left; TreeNode right; public TreeNode(char val) { this.val = val; } } /** * 创建一个...
List<TreeNode>treeNodeList=newArrayList<>();;publicList<TreeNode>dfs(TreeNoderoot){if(root==null){returnnull;}treeNodeList.add(root);//左侧递归,会一直找到最左的节点,找到后再回到根,再继续找dfs(root.left);//右侧递归,dfs(root.right);returntreeNodeList;} 接下来,我们把上述代码结构进行抽象,...
1publicvoidinorder(TreeNode root) {2if(root ==null) {3return;4}5inorder(root.left);6res.add(root.val);7inorder(root.right);8} (3)后序 1publicvoidpostorder(TreeNode root) {2if(root ==null) {3return;4}5postorder(root.left);6postorder(root.right);7res.add(root.val);8} 2、...
TreeNode(intx) { val = x; } }publicstaticvoidpreOrderTraversal(TreeNode root){if(root !=null) { System.out.print(root.val +" "); preOrderTraversal(root.left); preOrderTraversal(root.right); } }publicstaticvoidinOrderTraversal(TreeNode root){if(root !=null) { inOrderTraversal(root.l...
1、tree只有1个root作为BFS的源点,而图可以有多个源点,所以首先需要把多个源点都入队;或者认为图存在一个虚root,这些源点都是虚root的孩子 2、tree结构不存在回路,不需要标志某个节点是否访问过,但图必须标志节点是否已经被访问过。【可以额外使用字典/列表登记,但更巧的是直接原地修改元素值进行标记】 ...
importjava.util.Queue; publicclassT_BFS { publicvoidlevelOrderQueue(Node root){ Queue<Node> q =newLinkedList<Node>(); if(root ==null){ return; } q.add(root); while(!q.isEmpty()){ Node n = q.poll(); System.out.print(" "+ n.data); ...
int minDepth(TreeNode root) { if (root == null) return 0; Queue<TreeNode>q = new LinkedList<>(); q.offer(root); // root 本身就是一层,depth 初始化为 1 int depth = 1; while (!q.isEmpty()) { int sz = q.size(); /* 将当前队列中的所有节点向四周扩散 */ for (int i = ...
Meaning, that if BFS is run from a node s, then it will construct the tree only of those nodes reachable from s, but if there are other nodes in the graph, will not touch them. DFS however will continue its search through the entire graph, and construct the forest of all of these ...
Explanation :The BFS tree is the tree built during the execution of BFS on any graph. This lemma is true since at every point in the execution of BFS , we only traverse to the adjacent vertices of a vertex and thus every vertex in the queue is at max one level away from all other ...
接着我们遍历特殊节点,然后使用bfs算法来进行广度搜索,用dis变量来标记距离,如果距离大于d,就不再搜索,跳出循环!注意我们在进行广度搜索的时候要一次性处理一层节点!这也是while(size--)的作用,这种做法很类似于"之字形打印数组"。对于一个特殊节点,我们在dis变量的限制下尽可能的去搜索符合条件的节点,使用set用来判...