二叉树的三种遍历(OJ)

144. 二叉树的前序遍历

class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> ret = new ArrayList<>();
        if(root == null) {
            return ret;
        }
        ret.add(root.val);
        List<Integer> left =  preorderTraversal(root.left);
        List<Integer> right =  preorderTraversal(root.right);
        ret.addAll(left);
        ret.addAll(right);
        return ret;
    }
}

94. 二叉树的中序遍历

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> ret = new ArrayList<>();
        if(root == null) {
            return ret;
        }
        
        List<Integer> left = inorderTraversal(root.left);
        ret.addAll(left);
        ret.add(root.val);
        List<Integer> right = inorderTraversal(root.right);
        ret.addAll(right);
        return ret;
    }
}

145. 二叉树的后序遍历

class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> ret = new ArrayList<>();
        if(root == null) {
            return ret;
        }
        
        List<Integer> left = postorderTraversal(root.left);
        ret.addAll(left);
        List<Integer> right = postorderTraversal(root.right);
        ret.addAll(right);
        ret.add(root.val);
        return ret;
    }
}

你可能感兴趣的:(leetcode,算法,职场和发展)