二叉树的前、中、后序遍历的递归实现(Java实现)

  • 二叉树的前序、中序、后序遍历实际上是深度优先遍历(DFS)
  • 二叉树的层序遍历实际上是广度优先遍历(BFS)

二叉树的前序遍历

前序遍历:根结点 —> 左子树 —> 右子树
递归实现:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {

    private List<Integer> res = new ArrayList<>();

    public List<Integer> preorderTraversal(TreeNode root) {
        if (root == null) return res;
        if (root != null) {
            res.add(root.val);
        }
        if (root.left != null) {
            preorderTraversal(root.left);
        }    
        if (root.right != null) {
            preorderTraversal(root.right);
        }
        return res;
    }
}

对应于leetcode144

二叉树的中序遍历

中序遍历:左子树—> 根结点 —> 右子树
递归实现:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {

    private List<Integer> res = new ArrayList<>();  

    public List<Integer> inorderTraversal(TreeNode root) {
        if (root == null) return res;
        if (root.left != null) {
            inorderTraversal(root.left);
        }   
        if (root != null) {
            res.add(root.val);
        } 
        if (root.right != null) {
            inorderTraversal(root.right);
        }
        
        
        return res;
    }
}

对应于leetcode94

二叉树的后序遍历

后序遍历:左子树 —> 右子树 —> 根结点

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private List<Integer> res = new ArrayList<>();

    public List<Integer> postorderTraversal(TreeNode root) {
        if (root == null) return res;
        if (root.left != null) {
            postorderTraversal(root.left);
        }    
        if (root.right != null) {
            postorderTraversal(root.right);
        }
        if (root != null) {
            res.add(root.val);
        }
        
        return res;
    }
}

对应于leetcode145

猜你喜欢

转载自blog.csdn.net/bob_man/article/details/104990663