Binary Tree Postorder Traversal
来源:互联网 发布:织梦源码安装方法 编辑:程序博客网 时间:2024/05/19 17:57
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public List<Integer> postorderTraversal(TreeNode root) { //按照pre和in那样做 List<Integer> answer = new LinkedList<Integer>(); Stack<TreeNode> store = new Stack<TreeNode>();//用来存放根节点和右结点 Stack<String> rootorright = new Stack<String>(); //rootorright和store同步,记录下每次存入stack的是right还是root while(root != null)//Line 15: error: ';' expected While(root != null) while要小写 { if(root.left != null)//若左右均存在结点,先将根结点存入stack,将右结点存入stack,优先走左路 { store.push(root); rootorright.push("root"); if(root.right != null) { store.push(root.right); rootorright.push("right"); } root = root.left; } else if(root.right != null)//若不存在左结点而存在右结点,将根节点存入stack,走右路 { store.push(root); rootorright.push("root"); root = root.right; } else //若左右结点均不存在,将这个结点存入答案并让它变成null(防止对下一个循环的干扰),然后分两种情况 //如果这个结点本身是左结点,那下一个根结点就要选与之对应的右结点 //如果这个结点本身是右结点,那下一个根结点就要选与之对应的根结点 { answer.add(root.val); root = null; //if (!store.isEmpty()) root = store.pop(); //else break; //上面这个写法错误,不能起到删除原root的效果 if(!store.isEmpty()) { root = store.pop(); if(rootorright.pop() == "root" ) //当是stack里pop出root的时候,就将其左右结点均变成null,因为左右都已考察过了(因为根是最低优先级(后序是左右根)) { root.left = null; root.right = null; } } } } return answer; }}
0 0
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- 美国必将毁于烙印
- 数学基础:角度,弧度,三角函数
- EQ降龙18掌
- 备忘 windows 8.1 开发
- GitHub使用流程- Git Shell 的一些命令总结(二) 创建代码库并学会更新
- Binary Tree Postorder Traversal
- ObjectC语言基础4—ARC、成员变量、构造方法、property
- 获取来访IP和来访地址
- [leetcode] longest substring without repeating characters
- Webstorm & PhpStorm的序列号和证书
- 秉临戤戗眷聛戤傊驺讅櫽二礯惷彛
- 鼾斫惥麤嗰驗氐驢毵涑觱聭列增在明季
- 前锋培训java网址
- 2015年2月28