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