mirror of
https://github.com/chefyuan/algorithm-base.git
synced 2025-08-12 09:51:36 +00:00
添加Go语言题解
This commit is contained in:
@@ -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
|
||||
}
|
||||
```
|
||||
|
Reference in New Issue
Block a user