Binary Tree DFS Template

 1 /**
 2  * 本代码由九章算法编辑提供。没有版权欢迎转发。
 3  * - 九章算法致力于帮助更多中国人找到好的工作,教师团队均来自硅谷和国内的一线大公司在职工程师。
 4  * - 现有的面试培训课程包括:九章算法班,系统设计班,BAT国内班
 5  * - 更多详情请见官方网站:http://www.jiuzhang.com/
 6  */
 7 
 8 Template 1: Traverse
 9 
10 public class Solution {
11     public void traverse(TreeNode root) {
12         if (root == null) {
13             return;
14         }
15         // do something with root
16         traverse(root.left);
17         // do something with root
18         traverse(root.right);
19         // do something with root
20     }
21 }
22 
23 
24 Tempate 2: Divide & Conquer
25 
26 public class Solution {
27     public ResultType traversal(TreeNode root) {
28         // null or leaf
29         if (root == null) {
30             // do something and return;
31         }
32         
33         // Divide
34         ResultType left = traversal(root.left);
35         ResultType right = traversal(root.right);
36         
37         // Conquer
38         ResultType result = Merge from left and right.
39         return result;
40     }
41 }
原文地址:https://www.cnblogs.com/hygeia/p/4837090.html