二叉树的后序遍历
(牛客网—牛客题霸算法篇—NC192)
题目描述
给定一个二叉树,返回他的后序遍历的序列。
后序遍历是值按照 左节点->右节点->根节点 的顺序的遍历。
代码实现
import java.util.*;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}*/
public class Solution {
public void postOrder(List list,TreeNode root){
if(root!=null){
postOrder(list,root.left);
postOrder(list,root.right);
list.add(root.val);
}
}
public int[] postorderTraversal (TreeNode root) {
// write code here
ArrayList list=new ArrayList();
postOrder(list,root);
int[] result=new int[list.size()];
for(int i=0;i<list.size();i++){
result[i]=(int)list.get(i);
}
return result;
}
}