【LeetCode】Preorder, inorder and postorder traversal of binary tree

It is easier to do this question with recursion , and then according to the traversal characteristics of the front, middle and back:

The preamble is around the root ,

Inorder is left root right ,

Postorder is the left and right root .

 Pre-order traversal: entry to the question

class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if(root == null) return list;
        list.add(root.val); //先加入根节点
        list.addAll(preorderTraversal(root.left));  //再加入所有的左节点
        list.addAll(preorderTraversal(root.right)); //再加入所有的右节点 
        return list;
    }
}

 

In-order traversal: the entry to do the question

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>(); 
        if(root == null) return list;
        List<Integer> leftTree = inorderTraversal(root.left);
        list.addAll(leftTree); //左
        list.add(root.val); //根
        List<Integer> rightTree = inorderTraversal(root.right);
        list.addAll(rightTree); //右
        return list;
    }
}

 

Post-order traversal: entry to the question

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

 The topic is relatively simple. It seems that there are three topics. In fact, the code is in a different order. Generally speaking, it is quite simple. 

 

Guess you like

Origin blog.csdn.net/m0_73381672/article/details/131999691