我从此文学习到了很多http://blog.csdn.net/linhuanmars/article/details/22009351,对博主表示感谢。
我刚开始编的时候,对于非递归后序遍历二叉树的方法没有一个清晰的设想,只是粗略的想到了要用到栈,并且,对遍历时,当前节点的左右子树的存在与否分为4种情况,1左右子树均不存在 2左子树存在,右子树不存在等进行分类,并且对于子树的是否已经输出加以判断,代码如下:
/**
* 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) {
List<Integer> result=new ArrayList<Integer>();
if(root==null) return result;
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode prenode=null;
TreeNode node=root;
stack.push(node);
while(!stack.empty()) {
while(node.left!=null&&node.left!=prenode) {
node=node.left;
stack.push(node);
}
node=stack.peek();
if((node.left==null&&node.right==null)||(node.right==prenode)||(node.right==null&&node.left==prenode) ){
result.add(node.val);
prenode=node;
node=stack.pop();
}else{
//stack.push(node);
prenode=node;
node=node.right;
stack.push(node);
}
}
return result;
}
}
但是,对某些形状的二叉树处理出现错误。
看了文章开头所说的博客,我受到了很大的启发,反思一下自己的思路,发现了几个不完善的地方。对于遍历问题,不仅存在从上到下的遍历,还存在着从下到上的回溯。从下到上这一点,我在编程的时候并没有提到与从上到下一样的地位进行思考,只是简单的处理,这样便使得解决方案无法清晰的考虑到各种形状的二叉树。
之后的代码如下:
/**
* 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) {
List<Integer> result=new ArrayList<Integer>();
if(root==null) return result;
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode pre=null;
TreeNode cur=root;
stack.push(cur);
while(!stack.empty()) {
cur=stack.peek();
if(pre==null||pre.left==cur||pre.right==cur) {
if(cur.left!=null) {
pre=cur;
cur=cur.left;
stack.push(cur);
}else{
if(cur.right!=null) {
pre=cur;
cur=cur.right;
stack.push(cur);
}else{
result.add(cur.val);
pre=stack.pop();
}
}
}
if(cur.left==pre) {
if(cur.right==null) {
pre=stack.pop();
result.add(cur.val);
}else{
pre=cur;
cur=cur.right;
stack.push(cur);
}
}
if(cur.right==pre) {
pre=stack.pop();
result.add(cur.val);
}
}
return result;
}
}
这段代码一开始便采用2个指针,cur和pre识别遍历的方向和父节点与子节点的相互关系,更加抽象,使得问题的解决更加的容易。