# leetcode(145):Binary Tree Postorder Traversal

17 篇文章 1 订阅
6 篇文章 0 订阅

## 题目

Binary Tree Postorder Traversal
Given a binary tree, return the postorder traversal of its nodes’ values.

For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [3,2,1].

## 递归解法

/**
1. Definition for a binary tree node.
2. public class TreeNode {
3.     int val;
4.     TreeNode left;
5.     TreeNode right;
6.     TreeNode(int x) { val = x; }
7. }
*/
public class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
if (root != null) {
}
return list;
}
}

## 非递归解法

### 方法一

public class Solution {
private class StackNode {
TreeNode node;
boolean isFirst;
}
public List<Integer> postorderTraversal(TreeNode root) {
Stack<StackNode> stack = new Stack<StackNode>();
TreeNode node = root;
StackNode temp;
while (node != null || !stack.empty()) {
while (node != null) {//沿左子树一直往下搜索，直至出现没有左子树的结点
StackNode snode = new StackNode();
snode.node = node;
snode.isFirst = true;
stack.push(snode);
node = node.left;
}
if (!stack.empty()) {
temp = stack.pop();
if (temp.isFirst == true) {//第一次出现在暂定，保留在栈中，访问右孩子
temp.isFirst = false;
stack.push(temp);
node = temp.node.right;
}
else {//第二次出现在栈顶，则弹出栈
}
}
}
return list;
}
}

### 方法二

void postOrder3(BinTree *root)     //非递归后序遍历
{
stack<BinTree*> s;
BinTree *cur;                      //当前结点
BinTree *pre=NULL;                 //前一次访问的结点
s.push(root);
while(!s.empty())
{
cur=s.top();
if((cur->lchild==NULL&&cur->rchild==NULL)||
(pre!=NULL&&(pre==cur->lchild||pre==cur->rchild)))
{
cout<<cur->data<<" ";  //如果当前结点没有孩子结点或者孩子节点都已被访问过
s.pop();
pre=cur;
}
else
{
if(cur->rchild!=NULL)
s.push(cur->rchild);
if(cur->lchild!=NULL)
s.push(cur->lchild);
}
}
}

### 方法三

pre-order traversal is root-left-right, and post order is left-right-root. modify the code for pre-order to make it root-right-left, and then reverse the output so that we can get left-right-root .

1. Create an empty stack, Push root node to the stack.
2. Do following while stack is not empty.
2.1. pop an item from the stack and print it.
2.2. push the left child of popped item to stack.
2.3. push the right child of popped item to stack.
3. reverse the ouput.

• 1
点赞
• 0
收藏
觉得还不错? 一键收藏
• 打赏
• 0
评论
04-06 2023
09-15 520

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

ksisfighting

¥2 ¥4 ¥6 ¥10 ¥20

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。