2024.2.19
- 题目来源
- 我的题解
- 方法一 递归实现(深度优先遍历)
- 方法二 迭代实现(栈)
题目来源
力扣每日一题;题序:590
我的题解
方法一 递归实现(深度优先遍历)
与二叉树的后序遍历的递归实现相似,只是有些细节不一样
时间复杂度:O(n)
空间复杂度:O(n)
public List<Integer> postorder(Node root) {List<Integer> res=new ArrayList<>();if(root==null)return res;post(root,res);return res;
}
public void post(Node root,List<Integer> res){if(root==null)return ;// 细节的不同for(Node node:root.children){post(node,res);}res.add(root.val);
}
方法二 迭代实现(栈)
与二叉树的后序遍历的迭代实现相似,但是细节处不相同
时间复杂度:O(n)
空间复杂度:O(n)
public List<Integer> postorder(Node root) {List<Integer> res=new ArrayList<>();if(root==null)return res;LinkedList<Node> stack=new LinkedList<>();stack.push(root);Node pre=null;while(!stack.isEmpty()){Node cur=stack.peek();System.out.println(cur.children.size());//判断是否遍历完当前节点的所有子节点boolean f=false;for(Node node:cur.children){f|=node==pre;}//判断当前节点是否是叶子节点有所不同if(cur.children.size()==0||((pre!=null)&&f)){Node t=stack.pop();res.add(t.val);pre=t;}else{//从右往左压栈for(int i=cur.children.size()-1;i>=0;i--){Node node=cur.children.get(i);stack.push(node);}}}return res;
}
有任何问题,欢迎评论区交流,欢迎评论区提供其它解题思路(代码),也可以点个赞支持一下作者哈😄~