algorithm-base/animation-simulation/二叉树/二叉树的前序遍历(栈).md

122 lines
3.5 KiB
Java
Raw Normal View History

2021-05-13 06:28:39 +00:00
, ,`,,`.
![](https://img-blog.csdnimg.cn/20210504155755565.gif)
###
![image](https://cdn.jsdelivr.net/gh/tan45du/test@master/image.622242fm7dc0.png)
[1,2,3]
1 2 3
>
2021-05-21 10:34:13 +00:00
``
2021-05-13 06:28:39 +00:00
![](https://img-blog.csdnimg.cn/20210512205822221.gif)
2021-05-21 10:34:13 +00:00
`` root while
2021-05-13 06:28:39 +00:00
2021-07-23 15:44:19 +00:00
O(n)
2021-05-13 06:28:39 +00:00
2021-07-23 15:44:19 +00:00
O(n) O(logn) O(n)
2021-05-13 06:28:39 +00:00
****
```java
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
2021-07-27 18:26:32 +00:00
if (root == null) return list;
2021-05-13 06:28:39 +00:00
stack.push(root);
while (!stack.isEmpty()) {
2021-07-27 18:26:32 +00:00
TreeNode temp = stack.pop();
2021-05-13 06:28:39 +00:00
if (temp.right != null) {
stack.push(temp.right);
}
if (temp.left != null) {
stack.push(temp.left);
}
//这里也可以放到前面
list.add(temp.val);
}
return list;
}
}
```
2021-07-19 15:22:39 +00:00
Swift Code
```swift
class Solution {
func preorderTraversal(_ root: TreeNode?) -> [Int] {
var list:[Int] = []
var stack:[TreeNode] = []
guard root != nil else {
return list
}
stack.append(root!)
while !stack.isEmpty {
let temp = stack.popLast()
if let right = temp?.right {
stack.append(right)
}
if let left = temp?.left {
stack.append(left)
}
//这里也可以放到前面
list.append((temp?.val)!)
}
return list
}
}
```
2021-07-27 18:26:32 +00:00
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
}
```