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

99 lines
3.1 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
O(n)
O(n) O(logn) O(n)
****
```java
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
if (root == null) return list;
stack.push(root);
while (!stack.isEmpty()) {
TreeNode temp = stack.pop();
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
}
}
```