ð 145. äºåæ çååºéå
2022幎6æ9æ¥
- algorithm
ð 145. äºåæ çååºéå
éŸåºŠ: ð
é®é¢æè¿°
解æ³
/**
* 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 {
public List<Integer> postorderTraversal(TreeNode root) {
// æè·¯ïŒ
// è¿ä»£ - åå© èŸ
å©æ
// å
åºé¡ºåºäžº root -> left -> right
// ååºé¡ºåºäžº left -> right -> root
LinkedList<TreeNode> stack = new LinkedList<>();
LinkedList<Integer> tmpStack = new LinkedList<>();
if(root == null) {
return new ArrayList<Integer>();
}
// root != null
stack.push(root);
while(!stack.isEmpty()) {
TreeNode cur = stack.pop();
tmpStack.push(cur.val);
if(cur.left != null) {
stack.push(cur.left);
}
if(cur.right != null) {
stack.push(cur.right);
}
}
// tmpStack äžé¡ºåºäžº ååºéåçååº
List<Integer> res = new ArrayList<>();
while(!tmpStack.isEmpty()) {
res.add(tmpStack.pop());
}
return res;
}
}
èŸåº
è§£æ³ 2 - éåœ
/**
* 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<>();
public List<Integer> postorderTraversal(TreeNode root) {
// æè·¯ïŒ
// éåœ
mySol(root);
return res;
}
private void mySol(TreeNode root) {
// éåœç»æ¢æ¡ä»¶
if(root == null) {
return;
}
// root != null
mySol(root.left);
mySol(root.right);
res.add(root.val);
}
}