Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit28dc702

Browse files
edit 144
1 parent615ff78 commit28dc702

File tree

1 file changed

+10
-21
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+10
-21
lines changed

‎src/main/java/com/fishercoder/solutions/_144.java

Lines changed: 10 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,11 @@
22

33
importcom.fishercoder.common.classes.TreeNode;
44

5-
importjava.util.ArrayList;
6-
importjava.util.List;
7-
importjava.util.Stack;
5+
importjava.util.*;
86

9-
/**Given a binary tree, return the preorder traversal of its nodes' values.
7+
/**
8+
* 144. Binary Tree Preorder Traversal
9+
* Given a binary tree, return the preorder traversal of its nodes' values.
1010
1111
For example:
1212
Given binary tree {1,#,2,3},
@@ -20,21 +20,24 @@
2020
Note: Recursive solution is trivial, could you do it iteratively?*/
2121

2222
publicclass_144 {
23-
publicList<Integer>preorderTraversal_iterative_original(TreeNoderoot) {
23+
24+
publicList<Integer>preorderTraversal_iterative(TreeNoderoot) {
2425
List<Integer>list =newArrayList();
25-
Stack<TreeNode>stack =newStack();
2626
if(root ==null)returnlist;
27+
Deque<TreeNode>stack =newArrayDeque<>();
2728
stack.push(root);
2829
while(!stack.isEmpty()){
2930
TreeNodecurr =stack.pop();
3031
list.add(curr.val);
32+
/**We push right nodes onto the stack first, since they'll be popped out later than
33+
* the left nodes, to meet the preorder: root -> left -> right. */
3134
if(curr.right !=null)stack.push(curr.right);
3235
if(curr.left !=null)stack.push(curr.left);
3336
}
3437
returnlist;
3538
}
3639

37-
publicList<Integer>preorderTraversal_recursive_1(TreeNoderoot) {
40+
publicList<Integer>preorderTraversal_recursive(TreeNoderoot) {
3841
List<Integer>list =newArrayList();
3942
returnpre(root,list);
4043
}
@@ -47,18 +50,4 @@ List<Integer> pre(TreeNode root, List<Integer> list){
4750
returnlist;
4851
}
4952

50-
51-
publicList<Integer>preorderTraversal_recursive_2(TreeNoderoot) {
52-
List<Integer>result =newArrayList();
53-
if (root !=null)dfs(root,result);
54-
returnresult;
55-
}
56-
57-
privatevoiddfs(TreeNoderoot,List<Integer>result){
58-
result.add(root.val);
59-
if (root.left !=null)dfs(root.left,result);
60-
if (root.right !=null)dfs(root.right,result);
61-
}
62-
63-
6453
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp