Sequence traversal of binary tree

Posted by matt_4013 on Wed, 16 Feb 2022 11:09:54 +0100

1. Sequence traversal

Sequence traverses a binary tree. It is to traverse the binary tree layer by layer from left to right. In order to realize sequence traversal, we need to use an auxiliary data structure, namely queue. Queue first in first out conforms to the logic of layer by layer traversal, while stack first in last out is suitable for simulating depth first traversal, that is, recursive logic.

2. Examples

2.1 sequence traversal of binary tree

Sequence traversal of binary tree

Idea:
1. Create a queue to store nodes and a list set to store results
2. Record the results layer by layer.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> ans = new ArrayList<>();//Used to output results
        Queue<TreeNode> queue  = new LinkedList<>();//Create a queue to store layer by layer

        if(root==null) return ans;

        queue.offer(root);
        while(!queue.isEmpty()){
            List<Integer> list = new ArrayList<>();//Used to store values
            int len = queue.size();
            for(int i=0;i<len;i++){
                TreeNode temp = queue.poll();
                list.add(temp.val);//Put in the list

                if(temp.left!=null) queue.offer(temp.left);
                if(temp.right!=null) queue.offer(temp.right);

            }
            ans.add(list);
        }
        return ans;

    }
}

2.2 sequence traversal of binary tree II


Sequence traversal of binary tree II

Idea:
It is basically the same as the above question. You only need to reverse the result before outputting the result.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> ans = new ArrayList<>();//Used to output results
        Queue<TreeNode> queue  = new LinkedList<>();//Create a queue to store layer by layer

        if(root==null) return ans;

        queue.offer(root);
        while(!queue.isEmpty()){
            List<Integer> list = new ArrayList<>();//Used to store values
            int len = queue.size();
            for(int i=0;i<len;i++){
                TreeNode temp = queue.poll();
                list.add(temp.val);//Put in the list

                if(temp.left!=null) queue.offer(temp.left);
                if(temp.right!=null) queue.offer(temp.right);

            }
            ans.add(list);
        }
        //Just reverse ans
        List<List<Integer>> ans1 = new ArrayList<>();
        for(int i=ans.size()-1;i>=0;i--){
            ans1.add(ans.get(i));
        }
        return ans1;
        
        
    }
}

2.3 right view of binary tree


Right view of binary tree

The idea is the same as that of the template, except that the last element of the queue is added
if(i==len-1) {/ / ensure the current last child node
ans.add(temp.val);
}

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> ans = new ArrayList<>();//Used to output results
        Queue<TreeNode> queue = new LinkedList<>();//Queues are used to store nodes

        if(root==null) return ans;
        queue.offer(root);

        while(!queue.isEmpty()){
            int len = queue.size();

            for(int i=0;i<len;i++){
                TreeNode temp = queue.poll();
                if(i==len-1){//Ensure the current last child node
                    ans.add(temp.val);
                }
                if(temp.left!=null) queue.offer(temp.left);
                if(temp.right!=null) queue.offer(temp.right);
            }
        }
        return ans;
    }
}

2.4 layer average of binary tree


Layer average of binary tree

The template is still applied, but the value of each layer is recorded and output.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Double> averageOfLevels(TreeNode root) {
        List<Double> ans =new ArrayList<>();//Used to output answers
        Queue<TreeNode> queue = new LinkedList<>();//Used to store nodes

        if(root==null) return ans;

        queue.offer(root);//Queue nodes

        while(!queue.isEmpty()){
            
            int len = queue.size();
            Double sum = 0.0;

            for(int i = 0;i<len;i++){
                TreeNode temp = queue.poll();
                sum+=temp.val;
                
                if(temp.left!=null) queue.offer(temp.left);
                if(temp.right!=null) queue.offer(temp.right);

            }
            ans.add(sum/len);
        }
        return ans;
    }
}

2.5 sequence traversal of n-ary tree


Sequence traversal of N-ary tree

What we need to pay attention to is how to add child nodes.

/*
// Definition for a Node.
class Node {
    public int val;
    public List<Node> children;

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, List<Node> _children) {
        val = _val;
        children = _children;
    }
};
*/

class Solution {
    public List<List<Integer>> levelOrder(Node root) {
        List<List<Integer>> ans = new ArrayList<>();//Used to output answers
        Queue<Node>  queue = new LinkedList<>();//For storage nodes

        if(root==null) return ans;
        queue.offer(root);//Queue nodes

        while(!queue.isEmpty()){
            int len = queue.size();
            List<Integer> list = new ArrayList<>();//Record the value of each layer

            for(int i=0;i<len;i++){
                Node temp = queue.poll();
                list.add(temp.val);

                 List<Node> children = temp.children;//Record child nodes of temp
                 if(children==null||children.size()==0) continue;
                    for(Node child:children){
                        if(child!=null){//If the child node is not empty
                            queue.offer(child);//Add to queue
                        }
                    }


            }
            ans.add(list);
        }
        return ans;

    }
}

2.6 find the maximum value in each tree row


Find the maximum value in each tree row

Pay attention to collection Max() method, which outputs the maximum value in the set

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Integer> largestValues(TreeNode root) {
        List<Integer> ans = new ArrayList<>();//Used to output answers
        Queue<TreeNode> queue = new LinkedList<>();//Used to store nodes

        if(root==null) return ans;
        queue.offer(root);//Store current node

        while(!queue.isEmpty()){
            int len = queue.size();
            List<Integer> list = new ArrayList<>();//Used to record the value of each layer
            for(int i=0;i<len;i++){
                TreeNode temp = queue.poll();//Temporary storage node
                list.add(temp.val);//Record all values of the layer
                if(temp.left!=null) queue.offer(temp.left);
                if(temp.right!=null) queue.offer(temp.right);
            }
            ans.add(Collections.max(list));//Note collection max()
        }
        return ans;
    }
}

2.7 maximum depth of binary tree

Maximum depth of binary tree

After traversing each layer, the depth can be increased by one.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();//Storage node
        int depth=0;
        if(root==null) return depth;
        
        queue.offer(root);//Queue nodes

        while(!queue.isEmpty()){
            int len = queue.size();

            for(int i=0;i<len;i++){
                TreeNode temp = queue.poll();
                if(temp.left!=null) queue.offer(temp.left);
                if(temp.right!=null) queue.offer(temp.right);
                
            }
            depth++;//Number of layers plus one
        }
        return depth;
    }
}

2.8 minimum depth of binary tree


Minimum depth of binary tree

The depth of the left and right nodes should be null.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int minDepth(TreeNode root) {
        List<Integer> ans = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();

        if(root==null) return 0;
        queue.offer(root);//Root node queue
        int depth=0; 

        while(!queue.isEmpty()){
            depth++;//Every time you enter a layer, depth++
            int len = queue.size();
            for(int i=0;i<len;i++){
                TreeNode temp = queue.poll();
                //Find leaf node
                if(temp.left==null&&temp.right==null) return depth;

                if(temp.left!=null) queue.offer(temp.left);
                if(temp.right!=null) queue.offer(temp.right);
            }
        }
        return depth;

    }
}

Topics: Java leetcode linked list