diff --git a/problems/二叉树中递归带着回溯.md b/problems/二叉树中递归带着回溯.md index 603854dc..1e9f9cbf 100644 --- a/problems/二叉树中递归带着回溯.md +++ b/problems/二叉树中递归带着回溯.md @@ -171,7 +171,7 @@ if (cur->right) { ## 其他语言版本 -Java: +### Java: 100. 相同的树:递归代码 ```java class Solution { @@ -252,7 +252,7 @@ Java: } ``` -Python: +### Python: 100.相同的树 > 递归法 @@ -332,7 +332,7 @@ class Solution: self.traversal(cur.right, path+"->", result) #右 回溯就隐藏在这里 ``` -Go: +### Go: 100.相同的树 ```go @@ -436,7 +436,7 @@ func traversal(root *TreeNode,result *[]string,path *[]int){ } ``` -JavaScript: +### JavaScript: 100.相同的树 ```javascript @@ -515,7 +515,53 @@ var binaryTreePaths = function(root) { }; ``` -Swift: + +### TypeScript: + +> 相同的树 + +```typescript +function isSameTree(p: TreeNode | null, q: TreeNode | null): boolean { + if (p === null && q === null) return true; + if (p === null || q === null) return false; + if (p.val !== q.val) return false; + let bool1: boolean, bool2: boolean; + bool1 = isSameTree(p.left, q.left); + bool2 = isSameTree(p.right, q.right); + return bool1 && bool2; +}; +``` + +> 二叉树的不同路径 + +```typescript +function binaryTreePaths(root: TreeNode | null): string[] { + function recur(node: TreeNode, nodeSeqArr: number[], resArr: string[]): void { + nodeSeqArr.push(node.val); + if (node.left === null && node.right === null) { + resArr.push(nodeSeqArr.join('->')); + } + if (node.left !== null) { + recur(node.left, nodeSeqArr, resArr); + nodeSeqArr.pop(); + } + if (node.right !== null) { + recur(node.right, nodeSeqArr, resArr); + nodeSeqArr.pop(); + } + } + let nodeSeqArr: number[] = []; + let resArr: string[] = []; + if (root === null) return resArr; + recur(root, nodeSeqArr, resArr); + return resArr; +}; +``` + + + + +### Swift: > 100.相同的树 ```swift // 递归 @@ -571,5 +617,6 @@ func _binaryTreePaths3(_ root: TreeNode, res: inout [String], paths: inout [Int] } ``` + -----------------------