145. 二叉树的后序遍历 + 递归实现 + 非递归实现
145. 二叉树的后序遍历
LeetCode_145
题目描述
递归解法
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
List<Integer> list = new ArrayList<>();
public List<Integer> postorderTraversal(TreeNode root) {
inTravels(root);
return list;
}
public void inTravels(TreeNode now){
if(now == null)
return;
inTravels(now.left);
inTravels(now.right);
list.add(now.val);
}
}
非递归解法
再来看后序遍历,先序遍历是中左右,后续遍历是左右中,那么我们只需要调整一下先序遍历的代码顺序,就变成中右左的遍历顺序,然后在反转result数组,输出的结果顺序就是左右中了,如下图:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
List<Integer> list = new ArrayList<>();
public List<Integer> postorderTraversal(TreeNode root) {
Stack<TreeNode> sta = new Stack<>();
if(root == null)
return list;
sta.push(root);
while(!sta.isEmpty()){
TreeNode now = sta.pop();
list.add(now.val);
if(now.left != null)
sta.push(now.left);
if(now.right != null)
sta.push(now.right);
}
Collections.reverse(list);
return list;
}
}
Either Excellent or Rusty