[LeetCode]-Binary tree-6

Preface

Record the binary tree-related problems encountered in LeetCode brushing questions, Part 6

222.The number of nodes in a complete binary tree

The recursive function calculates the number of nodes in a tree rooted at a certain node: if the node is empty, the number of nodes is naturally 0; otherwise, the number of nodes should be equal to the current node 1 plus the sum of the node trees of the left and right subtrees.

 public int countNodes(TreeNode root) {
    
    
     if(root == null) return 0;
     return 1 + countNodes(root.left) + countNodes(root.right);
 }

Sword refers to Offer 32 - III. Print binary tree from top to bottom III

On the basis of level traversal, add a Boolean flag indicating whether the current level should be from left to right or right to left. If it is from left to right, it must be inserted into the list according to the tail insertion method; if it is from right to left, Just insert the list according to the head insertion method, and the resulting list is the traversal sequence of the current layer.

public List<List<Integer>> levelOrder(TreeNode root) {
    
    
    if(root == null) return new LinkedList<>();
    List<List<Integer>> res = new LinkedList<>();
    Deque<TreeNode> queue = new LinkedList<>();
    queue.addLast(root);
    //right标记,true时为从左向右;false时从右往左
    boolean right = true;
    while(!queue.isEmpty()){
    
    
        int size = queue.size();
        LinkedList<Integer> l = new LinkedList<>();
        for(int i = 0;i < size;i++){
    
    
            TreeNode poll = queue.poll();
            if(poll.left != null) queue.addLast(poll.left);
            if(poll.right != null) queue.addLast(poll.right);
            //从左往右时尾插,否则头插
            if(right) l.addLast(poll.val);
            else l.addFirst(poll.val);
        }
        res.add(l);
        //right取反
        right = !right;
    }
    return res;
}

226. Flip Binary Tree

Recursively flip the left subtree and right subtree, and then swap the left and right children of the current node.

public TreeNode invertTree(TreeNode root) {
    
    
    if(root == null) return null; //递归终点
    invertTree(root.left);        
    invertTree(root.right);
    TreeNode tmp = root.left;
    root.left = root.right;
    root.right = tmp;
    return root;
}

987. Vertical order traversal of binary tree

Ideas come from official solutions

public List<List<Integer>> verticalTraversal(TreeNode root) {
    
    
    //存储每个节点的信息,node[0]表示节点的row,node[1]表示节点的col,node[2]表示节点的值
    List<int[]> nodes = new ArrayList<int[]>();
    dfs(root,0,0,nodes);
    //对于每个节点的信息,优先按照列升序排序,其次是行,最后是节点值
    Collections.sort(nodes,(node1,node2) -> {
    
    
            if (node1[1] != node2[1]) {
    
    
                return node1[1] - node2[1];
            }else if (node1[0] != node2[0]) {
    
    
                return node1[0] - node2[0];
            }else {
    
    
                return node1[2] - node2[2];
            }
        }
    );
    List<List<Integer>> ans = new ArrayList<List<Integer>>();
    int index = -1; //记录ans中最新的元素
    int lastcol = Integer.MAX_VALUE; //记录ans中最新的元素所对应的列值
    for (int[] node : nodes) {
    
    
        int row = node[0], col = node[1], value = node[2];
        //如果当前节点的列跟ans中最新的元素对应的列值相等,则将该节点值也放入这个元素,否则创建一个新的列表
        //ans的元素即为每个列对应的节点的列表
        if (col != lastcol){
    
    
            lastcol = col;
            ans.add(new ArrayList<>());
            index++;
        }
        ans.get(index).add(value);
    }
    return ans;
}
//dfs搜索并记录每个节点的信息
public void dfs(TreeNode node, int row, int col, List<int[]> nodes) {
    
    
    if (node == null) {
    
    
        return;
    }
    nodes.add(new int[]{
    
    row, col, node.val});
    dfs(node.left, row + 1, col - 1, nodes);
    dfs(node.right, row + 1, col + 1, nodes);
}

297. Serialization and deserialization of binary trees

The binary tree is traversed in order to obtain the sequence string as the serialization result. Each node is separated by ',', and null is represented by "null".

When deserializing, use the String::split method to separate the sequence string with ',', and reconstruct the value of each node into a binary tree in the order of preorder traversal.

public class Codec {
    
    
    public String serialize(TreeNode root) {
    
    
        if(root == null){
    
    
            return "null";
        }
        //先序遍历
        return root.val + "," + serialize(root.left) + "," + serialize(root.right);  
    }
    public TreeNode deserialize(String data) {
    
    
        LinkedList<String> queue = new LinkedList<>(Arrays.asList(data.split(",")));
        return preorderToTree(queue);
    }
    //将先序遍历序列重构为二叉树
    private TreeNode preorderToTree(Queue<String> queue) {
    
    
        String val = queue.poll();
        if("null".equals(val)){
    
    
            return null;
        }
        TreeNode root = new TreeNode(Integer.parseInt(val));
        root.left = preorderToTree(queue);
        root.right = preorderToTree(queue);
        return root;
    }
}

129. Find the sum of numbers from the root node to the leaf nodes

This question uses the backtracking method: use res to record the sum of the currently obtained numbers, and the StringBuilder variable cur to record the currently obtained number. When the current node is a leaf node, convert the obtained cur into int and then accumulate it into res.
After traversing the nodes of the next level and returning to the current node, you need to go back and delete the last digit of cur.

class Solution {
    
    
    Integer res;
    StringBuilder cur;
    public int sumNumbers(TreeNode root) {
    
    
        res = 0;
        cur = new StringBuilder();
        backTrack(root);
        return res;
    }
    public void backTrack(TreeNode root){
    
    
        if(root == null) return;
        cur.append(root.val);
        if(root.left == null && root.right == null){
    
    
            res += Integer.valueOf(cur.toString());
            return;
        }
        if(root.left != null) {
    
    
            backTrack(root.left);
            //回退
            cur.deleteCharAt(cur.length() - 1);
        }
        if(root.right != null) {
    
    
            backTrack(root.right);
            //回退
            cur.deleteCharAt(cur.length() - 1);
        }
    }
}

543. Diameter of Binary Tree

After reading the meaning of the question, you can intuitively think that it is related to the depth of the node: the sum of the maximum depth of the left son of each node and the maximum depth of the right son is the maximum diameter corresponding to the node.

So we need to calculate the maximum depth of each node's left and right children. When calculating the maximum depth of a node, it is inevitably necessary to calculate the maximum depth of the left and right sons to get the maximum depth of the node, so we can use a recursive function to calculate the maximum depth of the node, in which the left and right children are calculated. When the son's maximum depth is maintained, the value of the maximum diameter is updated. When the maximum depth of all nodes is calculated, the value of the maximum diameter can be obtained.

class Solution {
    
    
    int res;
    public int diameterOfBinaryTree(TreeNode root) {
    
    
        maxDepth(root);
        return res;
    }
    public int maxDepth(TreeNode root) {
    
    
        if(root == null) return 0;
        //得到左右子树的最大深度
        int leftDepth = maxDepth(root.left);
        int rightDepth = maxDepth(root.right);
        //然后就可以更新整个子树最大直径的值
        res = Math.max(res,leftDepth + rightDepth);
        //最后再返回当前节点的最大深度
        return 1 + Math.max(leftDepth,rightDepth);
    }
}

Guess you like

Origin blog.csdn.net/Pacifica_/article/details/127162137