606. 根据二叉树创建字符串

1 先序遍历采用栈结构,每次把根节点出栈的时候 按照先右节点再左节点的方式入栈。
2 之前的先序遍历只是把节点数据入栈即可,这次我们需要涉及到括号 ,所以需要每次入栈的时候增加括号,按照先右括号 在左括号的方式入栈
3 唯一需要特殊处理的是 当左节点为空 但是右节点不为空的情况时候 需要入栈一个没有值的空括号
package mainimport ("fmt""strings")type TreeNode struct {Val intLeft *TreeNodeRight *TreeNode}func tree2str(t *TreeNode) string {var str strings.Builderif t == nil {return ""}stack := []interface{}{t}for len(stack) > 0 {node := stack[len(stack)-1]stack = stack[:len(stack)-1]if n, ok := node.(*TreeNode); ok {str.WriteString(fmt.Sprintf("%d", n.Val))if n.Right != nil {stack = append(stack, ")")stack = append(stack, n.Right)stack = append(stack, "(")}if n.Right != nil && n.Left == nil {stack = append(stack, "()")}if n.Left != nil {stack = append(stack, ")")stack = append(stack, n.Left)stack = append(stack, "(")}} else {s := node.(string)str.WriteString(s)}}return str.String()}func main() {one := &TreeNode{Val: 1}two := &TreeNode{Val: 2}one.Left = twothree := &TreeNode{Val: 3}one.Right = threefour := &TreeNode{Val: 4}two.Right = fourfmt.Println(tree2str(one))//one1 :=&TreeNode{Val: 1}//two1 :=&TreeNode{Val: 2}//one1.Left = two1//three1 :=&TreeNode{Val: 3}//one1.Right = three1//four1 :=&TreeNode{Val: 4}//two1.Right = four1//fmt.Println(tree2str(one1))}

