Skip to content

Commit 77a9976

Browse files
committed
144.二叉树的前序遍历-分解问题解法
1 parent 2c5c52d commit 77a9976

File tree

1 file changed

+18
-1
lines changed

1 file changed

+18
-1
lines changed

leetcode_Java/Solution0144.java

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919

2020

2121
/*
22-
* 递归思路:
22+
* 递归思路:遍历⼀遍⼆叉树,结果记录在全局变量中
2323
* 1、定义数据结构:使用列表成员变量,存储每次递归操作存入的值
2424
* 2、递归终止条件:节点为空时返回
2525
* 3、单层递归逻辑:把节点的值存入列表
@@ -42,6 +42,23 @@ public List<Integer> preorderTraversal(TreeNode root) {
4242
}
4343

4444

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+
return res;
58+
}
59+
}
60+
61+
4562
/*
4663
* 迭代思路:
4764
* 1、定义数据结构:局部变量即可,列表存放结果数据,栈按序存放节点,指针指向下一个要处理的节点

0 commit comments

Comments
 (0)