题目描述:

Given a binary tree, return the postorder traversal of its nodes' values.

思路:利用栈,以及头插法进行操作

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
import java.util.*;
public class Solution {
    public ArrayList<Integer> postorderTraversal(TreeNode root) {
        ArrayList<Integer> list=new ArrayList<>();
        Stack<TreeNode> stack=new Stack();
        if(root==null) 
            return list;
        stack.push(root);
        while(!stack.isEmpty()){
            TreeNode node=stack.pop();
            list.add(0,node.val);
            if(node.left!=null)
                stack.push(node.left);
            if(node.right!=null)
                stack.push(node.right);
        }
        return list;
    }
}

 

相关文章:

  • 2021-10-08
  • 2021-12-16
  • 2022-12-23
  • 2021-04-03
  • 2022-01-24
猜你喜欢
  • 2021-08-19
  • 2021-12-25
  • 2021-08-22
  • 2021-11-30
  • 2021-08-07
  • 2022-03-01
相关资源
相似解决方案