树
深度优先搜索
字符串
二叉树
题目描述
给你二叉树的根节点 root
,请你采用前序遍历的方式,将二叉树转化为一个由括号和整数组成的字符串,返回构造出的字符串。
空节点使用一对空括号对 "()"
表示,转化后需要省略所有不影响字符串与原始二叉树之间的一对一映射关系的空括号对。
示例 1:
输入: root = [1,2,3,4]
输出: "1(2(4))(3)"
解释: 初步转化后得到 "1(2(4)())(3()())" ,但省略所有不必要的空括号对后,字符串应该是"1(2(4))(3)" 。
示例 2:
输入: root = [1,2,3,null,4]
输出: "1(2()(4))(3)"
解释: 和第一个示例类似,但是无法省略第一个空括号对,否则会破坏输入与输出一一映射的关系。
提示:
树中节点的数目范围是 [1, 104 ]
-1000 <= Node.val <= 1000
解法
方法一
Python3 Java C++ Go TypeScript Rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution :
def tree2str ( self , root : Optional [ TreeNode ]) -> str :
def dfs ( root ):
if root is None :
return ''
if root . left is None and root . right is None :
return str ( root . val )
if root . right is None :
return f ' { root . val } ( { dfs ( root . left ) } )'
return f ' { root . val } ( { dfs ( root . left ) } )( { dfs ( root . right ) } )'
return dfs ( root )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29 /**
* 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 String tree2str ( TreeNode root ) {
if ( root == null ) {
return "" ;
}
if ( root . left == null && root . right == null ) {
return root . val + "" ;
}
if ( root . right == null ) {
return root . val + "(" + tree2str ( root . left ) + ")" ;
}
return root . val + "(" + tree2str ( root . left ) + ")(" + tree2str ( root . right ) + ")" ;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public :
string tree2str ( TreeNode * root ) {
if ( ! root ) return "" ;
if ( ! root -> left && ! root -> right ) return to_string ( root -> val );
if ( ! root -> right ) return to_string ( root -> val ) + "(" + tree2str ( root -> left ) + ")" ;
return to_string ( root -> val ) + "(" + tree2str ( root -> left ) + ")(" + tree2str ( root -> right ) + ")" ;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 /**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func tree2str ( root * TreeNode ) string {
if root == nil {
return ""
}
if root . Left == nil && root . Right == nil {
return strconv . Itoa ( root . Val )
}
if root . Right == nil {
return strconv . Itoa ( root . Val ) + "(" + tree2str ( root . Left ) + ")"
}
return strconv . Itoa ( root . Val ) + "(" + tree2str ( root . Left ) + ")(" + tree2str ( root . Right ) + ")"
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 /**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function tree2str ( root : TreeNode | null ) : string {
if ( root == null ) {
return '' ;
}
if ( root . left == null && root . right == null ) {
return ` ${ root . val } ` ;
}
return ` ${ root . val } ( ${ root . left ? tree2str ( root . left ) : '' } ) ${
root . right ? `( ${ tree2str ( root . right ) } )` : ''
} ` ;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48 // Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
// pub val: i32,
// pub left: Option<Rc<RefCell<TreeNode>>>,
// pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
// #[inline]
// pub fn new(val: i32) -> Self {
// TreeNode {
// val,
// left: None,
// right: None
// }
// }
// }
use std :: cell :: RefCell ;
use std :: rc :: Rc ;
impl Solution {
fn dfs ( root : & Option < Rc < RefCell < TreeNode >>> , res : & mut String ) {
if let Some ( node ) = root {
let node = node . borrow ();
res . push_str ( node . val . to_string (). as_str ());
if node . left . is_none () && node . right . is_none () {
return ;
}
res . push ( '(' );
if node . left . is_some () {
Self :: dfs ( & node . left , res );
}
res . push ( ')' );
if node . right . is_some () {
res . push ( '(' );
Self :: dfs ( & node . right , res );
res . push ( ')' );
}
}
}
pub fn tree2str ( root : Option < Rc < RefCell < TreeNode >>> ) -> String {
let mut res = String :: new ();
Self :: dfs ( & root , & mut res );
res
}
}
GitHub