//定义一个树节点
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
//非递归前序遍历
public void preorderTraversal_1(TreeNode node,List<Integer> list){
LinkedList<TreeNode> stack = new LinkedList<>();
while(!stack.isEmpty() || node != null){
while(node != null){
//访问当前结点
list.add(node.val);
stack.push(node);
node = node.left;
}
node = stack.pop();
node = node.right;
}
}
//非递归的中序遍历
//迭代算法 非递归写法 , 用栈去模拟递归
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
Deque<TreeNode> stk = new LinkedList<TreeNode>();
while (root != null || !stk.isEmpty()) {
while (root != null) {
stk.push(root);
root = root.left;
}
root = stk.pop();
res.add(root.val);
root = root.right;
}
return res;
}
//非递归的后序遍历 等价于 根右左的 反向序列
public void postorderTraversal_1(TreeNode node,List<Integer> list) {
Deque<TreeNode> stack = new LinkedList<>();
Deque<TreeNode> reverse_res = new LinkedList<>();
while(!stack.isEmpty() || node != null){
while(node != null){
stack.push(node);
reverse_res.push(node);
node = node.right;
}
node = stack.pop();
node = node.left;
}
TreeNode temp_node = null;
while(!reverse_res.isEmpty()){
temp_node = reverse_res.pop();
list.add(temp_node.val);
}
}
二叉树的遍历
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 树 在计算机科学中,树(英语:tree)是一种抽象数据类型或是实现这种抽象数据类型的数据结构,用来模拟具有树状结构...
- https://www.bilibili.com/video/BV15a4y1a7B5?from=search&s...
- 引言 无论是递归遍历还是非递归遍历,我们都无法将空间复杂度达到O(1),因为对于之前的遍历来说,它们都是使用栈的(...
- 引子:五分钟玩转面试考点-数据结构系列,不会像那种严肃、古板的教科书般的博客文章,而是将晦涩难懂的概念和知识点尽可...
- 二叉树层次遍历 按照二叉树中的层次从左到右依次遍历每层中的结点。具体的实现思路是:通过使用队列的数据结构,从树的根...