Easy questions related to LeetCode binary tree --- binary tree

Posted by iamtheironman on Sun, 16 Jan 2022 19:47:10 +0100

Question 1: merging binary trees

LeetCode 617 : Merge binary tree
Description:
Given two binary trees, imagine that when you overlay one of them on the other, some nodes of the two binary trees will overlap.
You need to merge them into a new binary tree. The merging rule is that if two nodes overlap, their values are added as the new value after node merging. Otherwise, the node that is not NULL will be directly used as the node of the new binary tree.

Problem solving ideas:

  1. Recursive two trees by preorder traversal
  2. Each recursion determines whether it is empty
    ① root1 is null, just return root2
    ② root2 is empty, just return root1
  3. Define a new tree merge. When recursive, add the values of the nodes of the two trees into the merge Val medium
  4. Recursively merge left and right subtrees;
  5. Finally, return to merge

Drawing analysis:

Code implementation:

class Solution {
    public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
        if(root1 == null){
            return root2;//root1 is null, and root2 is returned
        }
        if(root2 == null){
            return root1;//root2 is null, and root1 is returned
        }
        //Create a new node
        TreeNode merge = new TreeNode(root1.val + root2.val);
        //Left subtree of this node
        merge.left = mergeTrees(root1.left,root2.left);
        //Right subtree of this node
        merge.right = mergeTrees(root1.right,root2.right);
        return merge;//Return to this node
    }
}

Question 2: layer average of binary tree

LeetCode 637 : Layer average of binary tree
Description:
Given a non empty binary tree, return an array composed of the average value of nodes in each layer.

Problem solving ideas:

  1. Using the sequence traversal method, the values of each layer are added together
  2. Record the number of data in each layer
  3. The total of each layer ÷ the number of each layer is the average value of each layer
  4. Note the range of nodes here. The sum of each layer may exceed int, so long is used here

Drawing analysis:

Code implementation:

class Solution {
    public List<Double> averageOfLevels(TreeNode root) {
        List<Double> list = new ArrayList<>();
        if(root == null) return list;//Return directly if it is empty
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()){
            long sum = 0;//Sum is used to represent the sum of each layer
            int size = queue.size();
            int count = size;//count is used to represent the number of elements in each layer
            while(size != 0){
            	//When size is empty, it means that this layer has been recorded
                TreeNode top =queue.poll();
                sum += top.val;//Add data to sum every time you leave the team
                if(top.left != null){
                    queue.offer(top.left);
                }
                if(top.right != null){
                    queue.offer(top.right);
                }
                size--;
            }
            //Going out of the loop means the end of each layer, so put the obtained average value into the list
            list.add(sum / (count*1.0));
        }
        return list;
    }
}

Question 3: the second smallest node in a binary tree

LeetCode 671 : The second smallest node in a binary tree
Description:
Given a non empty special binary tree, each node is a positive number, and the number of child nodes of each node can only be 2 or 0. If a node has two child nodes, the value of the node is equal to the smaller of the two child nodes.
More formally, root Val = min (root.left.val, root. Right. VAL) is always established.
Given such a binary tree, you need to output the second smallest value of all nodes. If the second smallest value does not exist, output - 1.

Problem solving ideas:

  1. You can know that the root node must be the minimum
  2. Therefore, the method of preorder traversal is used to recurse the left subtree and the right subtree respectively
  3. Recursion returns directly as long as it finds a value larger than the root node. When the node is empty (not found), it returns - 1;
  4. If both the left and right subtrees have a value larger than the root node, the smaller value is returned
  5. If not on the left, return to the right
  6. If not on the right, return to the left
  7. If there are no on both sides, return - 1;

Drawing analysis:

Code implementation:

class Solution {
    public int findSecondMinimumValue(TreeNode root) {
        return getMinValue(root,root.val);
    }
    public int getMinValue(TreeNode root,int val){
        if(root==null) return -1; // Return - 1 larger than the root node is not found;
        if(root.val > val) return root.val;//If you find a node larger than the root node, return
        int left = getMinValue(root.left,val);//Left is the value of the left subtree
        int right = getMinValue(root.right,val);//Right is the value of the right subtree
        
        // If there is a value larger than the root node, the smaller one is returned
        if(left >=0 && right >= 0){
            return Math.min(left,right);
        }
        // If left has right, it does not return to left
        // If left has no right, return to right
        // If left is not right, no one is returned
        // The combination of the three cases is to return the largest one
        return Math.max(left,right);
    }
}

Question 4: trees with similar leaves

LeetCode 872 : Trees with similar leaves
Description:
Consider all the leaves in a binary tree. The values of these leaves are arranged from left to right to form a leaf value sequence.

For example, as shown in the figure above, a tree with leaf value sequence of (6, 7, 4, 9, 8) is given.
If the leaf value sequences of two binary trees are the same, we think they are leaf similar.
If the leaves of a given tree with two root nodes root1 and root2 are similar, return true; Otherwise, false is returned.

Problem solving ideas:

  1. Using the preorder traversal method, each recursion is stored in the list when the left and right subtrees of root are empty
  2. The recursion ends, and the list is the leaf node of the tree
  3. Comparing the list s of two trees, the same is true

Code implementation:

class Solution {
    public boolean leafSimilar(TreeNode root1, TreeNode root2) {
        // false if the list s of the two trees are different; otherwise, true;
        return getNode(root1).equals(getNode(root2));
    }


    public List<Integer> getNode(TreeNode root){
        List<Integer> list = new ArrayList<>();
        if(root == null) {
            return list;
        }
        // The left and right subtrees do not exist, that is, leaf nodes
        if(root.left == null && root.right == null){
            list.add(root.val);
        }
        list.addAll(getNode(root.left));
        list.addAll(getNode(root.right));
        return list;
    }
}

Topics: Algorithm data structure leetcode Binary tree