标签:out NPU bin == example lis public solution roo
Given a binary tree, return the postorder traversal of its nodes‘ values.
Example:
Input:[1,null,2,3]
1 2 / 3 Output:[3,2,1]
class Solution { public List<Integer> postorderTraversal(TreeNode root) { if (root == null) return new LinkedList(); Stack<TreeNode> s = new Stack<TreeNode>(); LinkedList<Integer> res = new LinkedList(); s.push(root); while(!s.empty()){ TreeNode p = s.pop(); res.addFirst(p.val); //左右根,push进stack是第一次逆,addFirst又逆回来,所以还是左右根 if(p.left != null){ s.push(p.left); } if(p.right != null){ s.push(p.right); } } return res; } }
LinkedList有addFirst方法,巧妙。
145. Binary Tree Postorder Traversal
标签:out NPU bin == example lis public solution roo
原文地址:https://www.cnblogs.com/wentiliangkaihua/p/11421651.html