Leet专题刷题Day02-DFS 二叉树
94. 二叉树的中序遍历
思路一:递归解法
class Solution {
List<Integer> res = new ArrayList<Integer>();
public List<Integer> inorderTraversal(TreeNode root) {
if (root == null) return res;
inorderTraversal(root.left);
res.add(root.val);
inorderTraversal(root.right);
return res;
}
}
思路二:迭代解法 先将所有左节点放入栈中,再pop出最左的节点,讲该节点的右节点作为左节点继续push到栈中,迭代即可。
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
Stack<TreeNode> stk = new Stack<TreeNode>();
while (root != null || !stk.isEmpty()) {
while (root != null) {
stk.push(root);
root = root.left;
}
root = stk.pop();
res.add(root.val);
root = root.right;
}
return res;
}
}
199. 二叉树的右视图
思路一:利用 BFS 进行层次遍历,记录下每层的最后一个元素。
class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null) {
return res;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
if (i == size - 1) { //将当前层的最后一个节点放入结果列表
res.add(node.val);
}
}
}
return res;
}
}
思路二:我们按照 「根结点 -> 右子树 -> 左子树」 的顺序访问,就可以保证每层都是最先访问最右边的节点的。
用depth记录深度,每一层之记录最右边的一个,如果深度和记录的是一样的,那么就可以记录。
class Solution {
List<Integer> res = new ArrayList<>();
public List<Integer> rightSideView(TreeNode root) {
dfs(root, 0);
return res;
}
private void dfs(TreeNode root, int depth) {
if (root == null) {
return;
}
// 先访问 当前节点,再递归地访问 右子树 和 左子树。
if (depth == res.size()) { // 如果当前节点所在深度还没有出现在res里,说明在该深度下当前节点是第一个被访问的节点,因此将当前节点加入res中。
res.add(root.val);
}
depth++;
dfs(root.right, depth);
dfs(root.left, depth);
}
}
226. 翻转二叉树
思路:dfs,每一层换一下。
class Solution {
public TreeNode invertTree(TreeNode root) {
dfs(root);
return root;
}
void dfs(TreeNode node){
if (node == null) return;
TreeNode temp = node.left;
node.left = node.right;
node.right = temp;
dfs(node.left);
dfs(node.right);
}
}
101. 对称二叉树
思路:dfs 用左边右边来递归。
class Solution {
private boolean helper(TreeNode left, TreeNode right){
//两边都是空,就是true
if(left == null && right == null) return true;
//只有一边空,false
if((left != null && right == null) || (left == null && right != null))
return false;
if(left.val != right.val) return false;
// 比对称 所以递归要递归中间和两边!
return helper(left.left, right.right) && helper(left.right, right.left);
}
public boolean isSymmetric(TreeNode root) {
return root == null ? true : helper(root.left, root.right);
}
}
104. 二叉树的最大深度
思路:简单的dfs
class Solution {
public int maxDepth(TreeNode root) {
return dfs(root, 0);
}
int dfs(TreeNode node, int depth){
if (node == null) return depth;
return Math.max(dfs(node.left, depth+1), dfs(node.right, depth+1));
}
}
617. 合并二叉树
class Solution {
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
if (t1 == null) {
return t2;
}
if (t2 == null) {
return t1;
}
TreeNode merged = new TreeNode(t1.val + t2.val);
merged.left = mergeTrees(t1.left, t2.left);
merged.right = mergeTrees(t1.right, t2.right);
return merged;
}
}
剑指 Offer 26. 树的子结构
思路:先比较头节点,如果一样继续比较。
class Solution {
public boolean isSubStructure(TreeNode A, TreeNode B) {
if(A == null || B == null) return false;
// 根节点相同后再进行比较子节点
if(A.val == B.val && isMatch(A, B)) return true;
return isSubStructure(A.left, B) || isSubStructure(A.right, B);
}
private boolean isMatch(TreeNode A, TreeNode B){
if(B == null) return true;
if(A == null) return false;
return A.val==B.val && isMatch(A.left, B.left) && isMatch(A.right, B.right);
}
}
236. 二叉树的最近公共祖先
思路:从root节点找,如果p q在同一侧就继续往那一侧找,如果两侧直接返回root。最终结果就是root就是p或q 或者p q两侧。
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null) return null;
// 如果p,q为根节点,则公共祖先为根节点
if (root.val == p.val || root.val == q.val) return root;
// 如果p,q在左子树,则公共祖先在左子树查找
if (find(root.left, p) && find(root.left, q)) {
return lowestCommonAncestor(root.left, p, q);
}
// 如果p,q在右子树,则公共祖先在右子树查找
if (find(root.right, p) && find(root.right, q)) {
return lowestCommonAncestor(root.right, p, q);
}
// 如果p,q分属两侧,则公共祖先为根节点
return root;
}
private boolean find(TreeNode root, TreeNode c) {
if (root == null) return false;
if (root.val == c.val) {
return true;
}
return find(root.left, c) || find(root.right, c);
}
}
98. 验证二叉搜索树
思路:没啥好说的,直接来
class Solution {
public boolean isValidBST(TreeNode root) {
return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
public boolean isValidBST(TreeNode node, long lower, long upper) {
if (node == null) {
return true;
}
if (node.val <= lower || node.val >= upper) {
return false;
}
return isValidBST(node.left, lower, node.val) && isValidBST(node.right, node.val, upper);
}
}
543. 二叉树的直径
思路:从根节点出发,分别计算每个节点的左右最深的长度
class Solution {
int max = 0;
public int diameterOfBinaryTree(TreeNode root) {
if (root == null) {
return 0;
}
dfs(root);
return max;
}
int dfs(TreeNode node){
if (node.left == null && node.right == null) {
return 0;
}
int left = node.left == null ? 0 : dfs(node.left)+1;
int right = node.right == null ? 0: dfs(node.right)+1;
max = Math.max(max, left+right);
return Math.max(left, right); // # 返回该节点为根的子树的深度
}
}
124. 二叉树中的最大路径和
思路:类似解法,增加如果是负数,就舍弃。
class Solution {
int max = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
dfs(root);
return max;
}
private int dfs(TreeNode root) {
if (root == null) {
return 0;
}
int leftSum = Math.max(0, dfs(root.left));
int rightSum = Math.max(0, dfs(root.right));
max = Math.max(max, leftSum + rightSum + root.val);
return Math.max(leftSum, rightSum) + root.val;
}
}
404. 左叶子之和
后序遍历,多加一个左叶子的判断
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
return dfs(root);
}
int dfs(TreeNode node){
int sum = 0;
if (node == null) return 0;
sum += dfs(node.left);
sum += dfs(node.right);
if (node.left != null && node.left.left == null && node.left.right == null){
sum += node.left.val;
return sum;
}
return sum;
}
}
257. 二叉树的所有路径
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> paths = new ArrayList<String>();
constructPaths(root, "", paths);
return paths;
}
public void constructPaths(TreeNode root, String path, List<String> paths) {
if (root != null) {
StringBuffer pathSB = new StringBuffer(path);
pathSB.append(Integer.toString(root.val));
if (root.left == null && root.right == null) { // 当前节点是叶子节点
paths.add(pathSB.toString()); // 把路径加入到答案中
} else {
pathSB.append("->"); // 当前节点不是叶子节点,继续递归遍历
constructPaths(root.left, pathSB.toString(), paths);
constructPaths(root.right, pathSB.toString(), paths);
}
}
}
}
剑指 Offer 36. 二叉搜索树与双向链表
思路:中序遍历,我们定义两个指针pre
和head
,pre
指针用于保存中序遍历的前一个节点,head
指针用于记录排序链表的头节点。
class Solution {
Node pre = null, head = null;
public Node treeToDoublyList(Node root) {
if (root == null) return root;
dfs(root);
head.left = pre;
pre.right = head;
return head;
}
void dfs(Node root){
if (root == null) return; // 递归边界: 叶子结点返回
dfs(root.left);
if (pre != null) pre.right = root;
else head = root; // 链表头结点
root.left = pre;
pre = root;
dfs(root.right);
}
}