树遍历非递归
2021/9/3 6:06:28
本文主要是介绍树遍历非递归,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
非递归的遍历模板
1.先序遍历 根左右
Stack<TreeNode> stack = new Stack<>(); while(!stack.isEmpty() || root != null){ while(root != null){ visit(根节点) stack.push(root); root = root.left; } root = stack.pop(); root = root.right; }
2.中序遍历 左根右
Stack<TreeNode> stack = new Stack<>(); while(!stack.isEmpty() || root != null){ while(root != null){ stack.push(root); root = root.left; } root = stack.pop(); visit(根节点) root = root.right; }
3.后序遍历 左右根
3.1 如果只是希望获得后序遍历结果
//观察可知 后序遍历为 左右根 ,逆序是 根右左,而先序遍历是 根左右 //所以只需要简单的改造先序遍历,使其变为根右左 //然后将访问结果reverse即为后序遍历结果 Stack<TreeNode> stack = new Stack<>(); List<Integer> list = new ArrayList<>(); while (!stack.isEmpty() || root != null) { while (root != null) { list.add(root.val); stack.push(root); root = root.right; } root = stack.pop(); root = root.left; } Collections.reverse(list);
3.2 若不仅仅只是想获得后序遍历结果,而是每次都需要进行一些处理
Stack<TreeNode> stack = new Stack<>(); List<Integer> list = new ArrayList(); TreeNode lastVisitedNode = null; while (!stack.isEmpty() || root != null) { while (root != null) { stack.push(root); root = root.left; } TreeNode topNode = stack.peek(); if (topNode.right != null && topNode.right != lastVisitedNode) root = topNode.right; else { stack.pop(); //visit(node) -- list.add(topNode.val); lastVisitedNode = topNode; } } return list
这篇关于树遍历非递归的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-07-08如何在敏捷项目中实现高效测试?
- 2024-07-08用户故事一定要有 “So that...” 吗?
- 2024-07-04TiDB 资源管控的对撞测试以及最佳实践架构
- 2024-07-03万字长文聊聊Web3的组成架构
- 2024-07-02springboot项目无法注册到nacos-icode9专业技术文章分享
- 2024-06-26结对编程到底难不难?答案在这里
- 2024-06-19《2023版Java工程师》课程升级公告
- 2024-06-15matplotlib作图不显示3D图,怎么办?
- 2024-06-1503-Loki 日志监控
- 2024-06-1504-让LLM理解知识 -Prompt