leetCode钻研6 二叉树的后序遍历
来源:互联网 发布:北京淘宝儿童模特 编辑:程序博客网 时间:2024/05/21 09:28
import java.util.Stack;
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> postorderTraversal(TreeNode root) {
TreeNode p=root,r=null;
Stack<TreeNode> s=new Stack<TreeNode>();
ArrayList<Integer> list=new ArrayList<Integer>();
while(p!=null||!s.isEmpty())
{
if(p!=null){
s.push(p);
p=p.left;
}
else{
p=s.peek();
p=p.right;
if(p!=null&&p!=r){
s.push(p);
p=p.left;
}
else{
p=s.pop();
list.add(p.val);
r=p;
p=null;
}
}
}
return list;
}}
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> postorderTraversal(TreeNode root) {
TreeNode p=root,r=null;
Stack<TreeNode> s=new Stack<TreeNode>();
ArrayList<Integer> list=new ArrayList<Integer>();
while(p!=null||!s.isEmpty())
{
if(p!=null){
s.push(p);
p=p.left;
}
else{
p=s.peek();
p=p.right;
if(p!=null&&p!=r){
s.push(p);
p=p.left;
}
else{
p=s.pop();
list.add(p.val);
r=p;
p=null;
}
}
}
return list;
}}
在while里,每一个节点都是一个服务对象,每一个节点都毫不犹豫的让自己的左节点优先考虑,这让我想到了父母与孩子的关系,令人感动。居然被一个算法感动了,真是莫名其妙,哈哈哈哈哈。
在while里的每一步看似是对各类节点的逐步划分,其实潜在的是为每一位客人设计好的格式。每一位进来,按格式来就好。自己没有习惯这个思维习惯,所有理解的比较慢。
有左的,p就成了左.。没左的了,就找右。右的又是先看左。。。。。。。最后把整个树后序遍历出来了,其实自己理解的还是不够透彻。非常不透彻
1 0
- leetCode钻研6 二叉树的后序遍历
- LeetCode钻研8 前序遍历树
- 二叉树的后序遍历(leetcode 145)
- LeetCode基础--二叉树--后序遍历
- LeetCode之通过二叉树的中序遍历和后序遍历还原二叉树
- leetcode 刷题: 后序遍历二叉树13
- 二叉树的后序遍历
- 二叉搜索树的后序遍历
- 二叉搜索树的后序遍历
- 二叉树的后序遍历
- 二叉搜索树的后序遍历
- 二叉树的后序遍历算法
- 题目:二叉树的后序遍历
- LintCode -- 二叉树的后序遍历
- Lintcode 二叉树的后序遍历
- 二叉搜索树的后序遍历
- LintCode:二叉树的后序遍历
- 二叉树的后序遍历
- Angular2文档学习的知识点摘要——模板语法
- 理解HTTP幂等性
- linus虚拟机装机1
- 需求变更管理和需求的可追溯性
- Git 常用命令大全
- leetCode钻研6 二叉树的后序遍历
- AndoidStudio常见问题解决
- 【Unity】最优化传递对象
- 菜鸟要做架构师(一)——如何快速开发中小型系统
- 简单的注册登录页面
- Unable to create unique key constraint (ID) on table XXX: ID not found
- Faker--伪造数据利器
- 区块链普及知识
- 阿甘正传小简介