Sequence Traversal of Binary Tree II

1. Demand

  • Given a binary tree, return the bottom-up traversal of its node values. (That is, from the layer where the leaf node is located to the layer where the root node is located, traverse from left to right layer by layer);

For example:
given a binary tree [3,9,20,null,null,15,7]

 3
   / \
  9  20
    /  \
   15   7

Return its bottom-up sequence traversal as:

[
  [15,7],
  [9,20],
  [3]
]

Two, BFS method 1

2.1 Thinking analysis

  1. According to the idea of printing the binary tree II from top to bottom: https://blog.csdn.net/Sruggle/article/details/108064919 , here is the last reversal of the list;

2.2 Code implementation

class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if(root == null) return res;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while(queue.size() != 0) {
            List<Integer> tmp = new ArrayList<>();
            int count = queue.size();
            while(count != 0) {
                TreeNode node = queue.poll();
                tmp.add(node.val);
                if(node.left != null) queue.add(node.left);
                if(node.right != null) queue.add(node.right);
                count--;
            }
            res.add(tmp);
        }
        Collections.reverse(res);
        return res;
    }
}

2.3 Complexity analysis

  • The time complexity is O(N), where N is the number of elements in the binary tree, and all elements need to be traversed;
  • The space complexity is O(N), and the queue can store up to N/2 elements at the same time;

Three, BFS method 2

3.1 Thinking analysis

  1. Using LinkedList, each row of the binary tree is added to the first position each time, which eliminates the complexity caused by the inversion in Method 2;

3.2 Code implementation

class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        LinkedList<List<Integer>> res = new LinkedList<>();
        if(root == null) return res;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while(queue.size() != 0) {
            List<Integer> tmp = new ArrayList<>();
            int count = queue.size();
            while(count != 0) {
                TreeNode node = queue.poll();
                tmp.add(node.val);
                if(node.left != null) queue.add(node.left);
                if(node.right != null) queue.add(node.right);
                count--;
            }
            res.addFirst(tmp);
        }
        return res;
    }
}

 

Guess you like

Origin blog.csdn.net/Sruggle/article/details/113376234