1 题目描述
给定一个二叉树,返回它的 后序 遍历。
示例:
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-preorder-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2 解题思路
二叉树的前中后序递归和非递归的做法参考下面的链接
二叉树的前中后层序遍历(递归、非递归Java实现)
3 解决代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
LinkedList<Integer> lists = new LinkedList<>();
if(root == null){
return lists;
}
Stack<TreeNode> stack = new Stack<>();
//根节点压入
stack.push(root);
TreeNode temp = null;
while(!stack.isEmpty()){
temp = stack.pop();
//LinkedList 集合类 void addFirst(Object o) 在列表首部添加元素
lists.addFirst(temp.val);
//先压入左节点,再压入右节点
if(temp.left != null){
stack.push(temp.left);
}
if(temp.right != null){
stack.push(temp.right);
}
}
return lists;
}
}