We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 2c5c52d commit 77a9976Copy full SHA for 77a9976
leetcode_Java/Solution0144.java
@@ -19,7 +19,7 @@
19
20
21
/*
22
-* 递归思路:
+* 递归思路:遍历⼀遍⼆叉树,结果记录在全局变量中
23
* 1、定义数据结构:使用列表成员变量,存储每次递归操作存入的值
24
* 2、递归终止条件:节点为空时返回
25
* 3、单层递归逻辑:把节点的值存入列表
@@ -42,6 +42,23 @@ public List<Integer> preorderTraversal(TreeNode root) {
42
}
43
44
45
+/*
46
+递归思路:分解问题计算出答案。通过维护局部变量,存放子问题的结果,将子结果返回给上一层使用,层层累计处理,得到最终结果
47
+ */
48
+class Solution {
49
+ public List<Integer> preorderTraversal(TreeNode root) {
50
+ List<Integer> res = new ArrayList<>();
51
+ if (root == null) {
52
+ return res;
53
+ }
54
+ res.add(root.val);
55
+ res.addAll(preorderTraversal(root.left));
56
+ res.addAll(preorderTraversal(root.right));
57
58
59
+}
60
+
61
62
63
* 迭代思路:
64
* 1、定义数据结构:局部变量即可,列表存放结果数据,栈按序存放节点,指针指向下一个要处理的节点
0 commit comments