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