Leetcode之二叉树和图

196 阅读3分钟

Js源码

github.com/zsjun/leetc…

113. Path Sum II

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

Note: A leaf is a node with no children.

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] ] 思考路程 1 递归遍历即可

236. Lowest Common Ancestor of a Binary Tree

  1. Lowest Common Ancestor of a Binary Tree

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

Given the following binary tree: root = [3,5,1,6,2,0,8,null,null,7,4]

Example 1:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 Output: 3 Explanation: The LCA of nodes 5 and 1 is 3. Example 2:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4 Output: 5 Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.

Note:

All of the nodes' values will be unique. p and q are different and both values will exist in the binary tree.

思考路程 1 直接遍历即可 114. Flatten Binary Tree to Linked List Given a binary tree, flatten it to a linked list in-place.

For example, given the following tree:

1 /
2 5 / \
3 4 6 The flattened tree should look like:

1
2
3
4
5
6

思考路程 1 很简单,之间中序遍历,即可

207. Course Schedule

There are a total of numCourses courses you have to take, labeled from 0 to numCourses-1.

Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]

Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?

Example 1:

Input: numCourses = 2, prerequisites = [[1,0]] Output: true Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible. Example 2:

Input: numCourses = 2, prerequisites = [[1,0],[0,1]] Output: false Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.

Constraints:

The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented. You may assume that there are no duplicate edges in the input prerequisites. 1 <= numCourses <= 10^5

思考路程 1, 问题可以转换为如何判断有向图中是否有环,如果没有环,则可以全部学完全部课程,如果有环,则肯定学不完 那么如何判断是否有环呢? 1.1 本来想根据一个visited数组,把访问过的都标记,这样来不断深度搜索,最后发现,逻辑自己都被搞混了,而且好多测试用例过不去,干脆放弃 1.2 可以判断是否存在入度为0的节点,如果存在则去掉,同时更新和该节点联系的入度,如果最后发现还是存在节点,则说明存在环

心得: 逻辑如果自己设想的太复杂,或者边界太多,基本上就说明该算法是不正确的,算法算法,是首先在脑中实现,是靠脑子调试,而不是靠调试器