添加Go语言题解

This commit is contained in:
zouxinyao
2021-07-28 02:26:32 +08:00
parent 7eb8b4a9fd
commit 575b7612f0
52 changed files with 1679 additions and 104 deletions

View File

@@ -49,10 +49,10 @@ class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
if (root == null) return list;
if (root == null) return list;
stack.push(root);
while (!stack.isEmpty()) {
TreeNode temp = stack.pop();
TreeNode temp = stack.pop();
if (temp.right != null) {
stack.push(temp.right);
}
@@ -95,3 +95,27 @@ class Solution {
}
}
```
Go Code:
```go
func preorderTraversal(root *TreeNode) []int {
res := []int{}
if root == nil {
return res
}
stk := []*TreeNode{root}
for len(stk) != 0 {
temp := stk[len(stk) - 1]
stk = stk[: len(stk) - 1]
if temp.Right != nil {
stk = append(stk, temp.Right)
}
if temp.Left != nil {
stk = append(stk, temp.Left)
}
res = append(res, temp.Val)
}
return res
}
```