Cracking the coding interview--Q4

Chapter 4 | Trees and Graphs

4.1 Implement a function to check if a tree is balanced. For the purposes of this question, a balanced tree is defined to be a tree such that no two leaf nodes differ in distance from the root by more than one.

遍历,当叶子时记录值

4.2 Given a directed graph, design an algorithm to find out whether there is a route between two nodes.

不是很会写树的代码。需要熟悉一下,BFS过程倒是看懂了,就是把树当成二维数组不断的尝试往树枝访问,用到了栈(感觉没必要)。修改的代码就是中途判断了下是否是dst节点。

4.3 Given a sorted (increasing order) array, write an algorithm to create a binary tree with minimal height.

想法很简单,就是二分,不断二分就可以得到最小树。要考虑边界条件。

4.4 Given a binary search tree, design an algorithm which creates a linked list of all the nodes at each depth (i.e., if you have a tree with depth D, you’ll have D linked lists).

BFS的过程。。应该也会用到上面栈的思想?不用也可以。看了下原解确实如此。

4.5 Write an algorithm to find the ‘next’ node (i.e., in-order successor) of a given node in a binary search tree where each node has a link to its parent.

就往parent和rchild找

4.6 Design an algorithm and write code to find the first common ancestor of two nodes in a binary tree. Avoid storing additional nodes in a data structure. NOTE: This is not necessarily a binary search tree.

题意不清

4.7 You have two very large binary trees: T1, with millions of nodes, and T2, with hun- dreds of nodes. Create an algorithm to decide if T2 is a subtree of T1.

没有好方法。

4.8 You are given a binary tree in which each node contains a value. Design an algorithm to print all paths which sum up to that value. Note that it can be any path in the tree – it does not have to start at the root.

倒序求和。

你可能感兴趣的:(Cracking the coding interview--Q4)