2023年6月22日发(作者:)
⼆叉树的遍历算法(DFS和BFS)⼆叉树的遍历算法(DFS和BFS)/* Definition for a binary tree node. */public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; }}深度优先遍历(DFS)迭代算法前序遍历(先访问根节点)⽤⼀个stack进⾏辅助class Solution { public List
} return res; }}⽅法⼆:⽤了两个stack进⾏辅助,思路是将待访问的节点按照逆序push进stack2,然后遍历stack2的顺序即为后续遍历的顺序。之所以能够这么做是因为我们最先访问的节点是⽗节点,这个节点在后续遍历中最后访问,我们就可以将它最先push进stack2,然后再push右⼦节点、左⼦节点。在push右⼦节点时,它本⾝也是⼀个⽗⼦节点,所以再push它的右⼦节点、左⼦节点。这种递归关系被保存在stack1中,使得节点按照顺序push进stack2中。class Solution { public List
} while(!y()){ (().val); } return res; }}递归算法递归算法⽐较简单,这⾥不再赘述迭代算法与递归算法⽐较因为每⼀个节点都要被访问,所以两种⽅法的时间复杂度都为O(N)。对于空间复杂度,递归算法的空间复杂度为O(N),当树很⼤时,会出现stackoverflow的问题。迭代算法由于借助了stack,最坏的情况下节点全部⼊栈,因此空间复杂的也为O(N),同样存在stackoverflow的问题。值得注意的是,有⼀种迭代算法可以将空间复杂度降低到O(1),它就是Morris迭代算法。⼴度优先遍历(BFS)递归算法class Solution { public List } level++; } return res; }}迭代算法与递归算法⽐较两种算法的时间复杂度和空间复杂度都为O(N)。> levelOrder(TreeNode root) { List
> res = new ArrayList<>(); if(root == null) return res; helper(root, 0, res); return res; } public void helper(TreeNode node, int level, List
> res){ if(() == level) //如果没有这⼀层,则创建它 (new ArrayList
> levelOrder(TreeNode root) { List
> res = new ArrayList<>(); if(root == null) return res; Queue
发布者:admin,转转请注明出处:http://www.yc00.com/xiaochengxu/1687384585a6064.html
评论列表(0条)