1. 前序遍历(根-左-右)

import java.util.*;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

public class BinaryTreeDFS {
    
    // 前序遍历 - 迭代版
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (root == null) return result;
        
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            result.add(node.val);
            
            // 先右后左,保证左子树先被处理
            if (node.right != null) {
                stack.push(node.right);
            }
            if (node.left != null) {
                stack.push(node.left);
            }
        }
        
        return result;
    }
}

2. 中序遍历(左-根-右)

// 中序遍历 - 迭代版
public List<Integer> inorderTraversal(TreeNode root) {
    List<Integer> result = new ArrayList<>();
    Stack<TreeNode> stack = new Stack<>();
    TreeNode curr = root;
    
    while (curr != null || !stack.isEmpty()) {
        // 遍历到最左边的节点
        while (curr != null) {
            stack.push(curr);
            curr = curr.left;
        }
        
        // 处理当前节点
        curr = stack.pop();
        result.add(curr.val);
        
        // 转向右子树
        curr = curr.right;
    }
    
    return result;
}

3. 后序遍历(左-右-根)

// 后序遍历 - 迭代版(使用两个栈)
public List<Integer> postorderTraversal(TreeNode root) {
    List<Integer> result = new ArrayList<>();
    if (root == null) return result;
    
    Stack<TreeNode> stack1 = new Stack<>();
    Stack<TreeNode> stack2 = new Stack<>();
    stack1.push(root);
    
    while (!stack1.isEmpty()) {
        TreeNode node = stack1.pop();
        stack2.push(node);
        
        if (node.left != null) {
            stack1.push(node.left);
        }
        if (node.right != null) {
            stack1.push(node.right);
        }
    }
    
    while (!stack2.isEmpty()) {
        result.add(stack2.pop().val);
    }
    
    return result;
}

// 后序遍历 - 单栈版本(更高效)
public List<Integer> postorderTraversalSingleStack(TreeNode root) {
    List<Integer> result = new ArrayList<>();
    if (root == null) return result;
    
    Stack<TreeNode> stack = new Stack<>();
    TreeNode prev = null; // 记录前一个访问的节点
    TreeNode curr = root;
    
    while (curr != null || !stack.isEmpty()) {
        // 遍历到最左边的节点
        while (curr != null) {
            stack.push(curr);
            curr = curr.left;
        }
        
        curr = stack.peek();
        
        // 如果右子树为空或已经访问过,则访问当前节点
        if (curr.right == null || curr.right == prev) {
            result.add(curr.val);
            stack.pop();
            prev = curr;
            curr = null;
        } else {
            // 否则转向右子树
            curr = curr.right;
        }
    }
    
    return result;
}
分类: DS-Algo 标签: Java

评论

暂无评论数据

暂无评论数据

目录