参考:史上最全遍历二叉树详解
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
List<Integer> res;
public List<Integer> postorderTraversal(TreeNode root) {
Stack<TreeNode> s = new Stack<>();
res = new ArrayList<>();
if(root == null) return res;
TreeNode cur = root, pre = null;
while(cur != null)
{
pre = cur.left;
if(pre != null)
{
while(pre.right != null && pre.right != cur)
pre = pre.right;
if(pre.right == null)
{
pre.right = cur;
// res.add(cur.val); //pre
cur = cur.left;
continue;
}
else
{
pre.right = null;
MorrisPrint(cur.left);
}
}
// else
// {
// res.add(cur.val); //pre
// }
// res.add(cur.val); //inorder
cur = cur.right;
}
MorrisPrint(root);
return res;
}
public void MorrisPrint(TreeNode root)
{
root = reverseList(root);
TreeNode tmp = root;
while(tmp != null)
{
res.add(tmp.val);
tmp = tmp.right;
}
root = reverseList(root);
}
public TreeNode reverseList(TreeNode root)
{
TreeNode pre = null;
while(root != null)
{
TreeNode next = root.right;
root.right = pre;
pre = root;
root = next;
}
return pre;
}
}