二叉树中使用深度优先搜索(DFS)的几种经典代码形式总结

DFS在二叉树中运用示例

    • 示例 1:经典 DFS 遍历(先序遍历)
    • 示例 2:DFS + 回溯(如路径问题)
    • 示例 3:DFS 判断平衡二叉树(递归 + 剪枝)
    • 示例 4:DFS 用于路径和为目标值(LeetCode 112)
    • 示例 5:判断是否是相同的树
    • 总结:DFS 模板结构

示例 1:经典 DFS 遍历(先序遍历)

public class Solution {
    public void dfs(TreeNode root) {
        if (root == null) return;

        // 访问当前节点(前序)
        System.out.print(root.val + " ");

        // 遍历左子树
        dfs(root.left);

        // 遍历右子树
        dfs(root.right);
    }
}

示例 2:DFS + 回溯(如路径问题)

例如用于「找所有根到叶路径」:

public class Solution {
    public List<String> res = new ArrayList<>();

    public List<String> binaryTreePaths(TreeNode root) {
        dfs(root, "");
        return res;
    }

    public void dfs(TreeNode node, String path) {
        if (node == null) return;

        // 当前路径拼接
        if (!path.isEmpty()) path += "->";
        path += node.val;

        // 到达叶子节点
        if (node.left == null && node.right == null) {
            res.add(path);
            return;
        }

        dfs(node.left, path);
        dfs(node.right, path);
    }
}

示例 3:DFS 判断平衡二叉树(递归 + 剪枝)

public class Solution {
    public boolean isBalanced(TreeNode root) {
        return height(root) != -1;
    }

    public int height(TreeNode node) {
        if (node == null) return 0;

        int left = height(node.left);
        if (left == -1) return -1;

        int right = height(node.right);
        if (right == -1) return -1;

        if (Math.abs(left - right) > 1) return -1;

        return Math.max(left, right) + 1;
    }
}

示例 4:DFS 用于路径和为目标值(LeetCode 112)

public class Solution {
    public boolean hasPathSum(TreeNode root, int targetSum) {
        if (root == null) return false;

        // 到达叶子节点,检查路径和
        if (root.left == null && root.right == null) {
            return targetSum == root.val;
        }

        // 递归左/右子树
        return hasPathSum(root.left, targetSum - root.val) || 
               hasPathSum(root.right, targetSum - root.val);
    }
}

示例 5:判断是否是相同的树

class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if(p == null&&q == null){
            return true;
        }else if(p==null || q==null){
            return false;
        }else if(p.val != q.val){
            return false;
        }else{
            return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
        }
    }
}

总结:DFS 模板结构

void dfs(TreeNode node) {
    if (node == null) return;

    // 访问当前节点
    // dfs 前序处理逻辑

    dfs(node.left);  // 递归左子树
    // dfs 中序处理逻辑
    dfs(node.right); // 递归右子树
    // dfs 后序处理逻辑
}

你可能感兴趣的:(深度优先,算法)