一、题目
Given a binary tree, return the Postorder traversal of its nodes’ values.
===> D E B F C A
二、演示
当时看别人的代码,刚开始怎么也看不懂,像这样拿笔在纸上多画画就明白了
三、代码实现
/*** 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) {
List<Integer> result = new ArrayList<>();TreeNode node = root;Stack<TreeNode> stack=new Stack<>();if(node !=null)stack.push(node);while (!stack.isEmpty()){
node = stack.pop();if(node.left != null){
stack.push(node.left);}if(node.right != null){
stack.push(node.right);}result.add(0,node.val);}return result;}
}