题目:二叉树的后序遍历
二叉树有3种遍历方式:
1,前序遍历,2,中序遍历,3,后序遍历
后序遍历的逻辑就是:先左子节点,再右子节点,最后跟节点。
举例如图:
左右子节点分别为:那咱们发现,左子节点,是一大坨啊。咋遍历呢?
依然是后序遍历拆分。
所以就是4-5-2-3-1
代码
/**
* 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> res = new ArrayList<Integer>();
public void fun(TreeNode node){
if (node!=null){
TreeNode left = node.left;
TreeNode right = node.right;
fun(left);
if (left!=null)
res.add(left.val);
fun(right);
if (right!=null)
res.add(right.val);
}
}
public List<Integer> postorderTraversal(TreeNode root) {
fun(root);
if (root!=null)
res.add(root.val);
return res;
}
}