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

70 lines
2.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
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;
}
}
```