Summary 606 of Likou Solution - Create a String from a Binary Tree

Directory link:

Likou Programming Questions - Solution Summary - Sharing + Recording - CSDN Blog

GitHub synchronous brushing project:

https://github.com/September26/java-algorithms

https://github.com/September26/java-algorithms

Original title link: force buckle


describe:

You need to use a preorder traversal to convert a binary tree into a string consisting of parentheses and integers.

Empty nodes are represented by a pair of empty parentheses "()". And you need to omit all pairs of empty parentheses that don't affect the one-to-one mapping between strings and the original binary tree.

Example 1:

Input: Binary tree: [1,2,3,4]
       1
     / \
    2 3
   /    
  4     

Output: "1(2(4))(3)"

Explanation: Originally it would be "1(2(4)())(3())", it will be "1(2(4))(3)"
after you omit all unnecessary pairs of empty parentheses
.
Example 2:

Input: Binary tree: [1,2,3,null,4]
       1
     / \
    2 3
     \  
      4 

Output: "1(2()(4))(3)"

Explanation: Similar to the first example,
except we cannot omit the first pair of parentheses to break the one-to-one mapping between input and output.

Source: LeetCode
Link: https://leetcode-cn.com/problems/construct-string-from-binary-tree The
copyright belongs to Leetcode.com. For commercial reprints, please contact the official authorization, and for non-commercial reprints, please indicate the source.

Problem solving ideas:

* Problem-solving ideas: 
* Today's question is not clearly described. There is one less rule. It should be that the left node is empty, and when the right node is not empty, the left node should be recorded as (). 
* First perform pre-order traversal recursively, use stringbuilder to record

Code:

public class Solution606 {
    public String tree2str(TreeNode root) {
        StringBuilder builder = new StringBuilder();
        search(root, builder);
        return builder.toString();
    }

    private void search(TreeNode root, StringBuilder builder) {
        if (root == null) {
            return;
        }
        builder.append(root.val);

        //左节点为空,右节点不为空时,左节点要记录成()
        if (root.left != null || root.right != null) {
            builder.append("(");
            search(root.left, builder);
            builder.append(")");
        }
        //右节点为空就不记录
        if (root.right != null) {
            builder.append("(");
            search(root.right, builder);
            builder.append(")");
        }
    }

}

Guess you like

Origin blog.csdn.net/AA5279AA/article/details/123592353