二叉树的重点内容就是遍历。前序、中序、后序遍历的区别在于操作处理的先后。
1、路净总和II lc113
问题:给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。
分析:遍历递归+栈
- 遍历到叶子节点,保存路径的结点值(栈的思想,可以用LinkedList),返回结果用双重List。
- 判断的条件为①叶子结点,即left和right都为null,②sum值为目标值。
- 边界:返回的过程只有左结点或者右结点时,递归处理过程的判空。
- 进栈—>访问操作—>左递归—>右递归—>出栈。
代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public LinkedList<Integer> cur = new LinkedList<>();
public List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> pathSum(TreeNode root, int sum) {
travel(root, sum);
return res;
}
public void travel(TreeNode node, int sum) {
if (node == null)
return;
cur.add(node.val);
if (node.left == null && node.right == null && sum == node.val) {
List<Integer> path = new ArrayList<>(cur);
res.add(path);
}
travel(node.left, sum - node.val);
travel(node.right, sum - node.val);
cur.remove(cur.size() - 1);
}
}
2、二叉树的最近公共祖先【经典】 lc236
摘要:LCA问题(最近公共祖先 Lowest Common Ancestor)、递归、BFS、剪枝DFS
问题:给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
分析:遍历+栈
- 采用的是
代码:
- 法1:直接的BFS
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null)
return null; // 遍历到叶子结点,返回null
if (root == p || root == q)
return root; // 遍历到p或者q,则返回p或者q
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if (left != null && right != null)
return root; // 左右都不为空,找到最近祖先,返回root
else if (left != null)
return left; // 找到左则返回左,右边继续找
else if (right != null)
return right; // 找到右侧返回右,左边继续找
return null;
}
}
- 法2:采用存储父节点,通过DFS或者BFS搜索到对应元素后,在栈中对比