Algorithm
102 Binary Tree Level Order Traversal
解题思路:
- 使用bfs一层一层的遍历,将结果存储在list中
/**
* 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<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if(root == null)
return result;
Deque<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
while(!queue.isEmpty()){
int level_size = queue.size();
List<Integer> current_level = new ArrayList<Integer>();
for(int i = 0; i < level_size; i++){
TreeNode node = queue.pop();
current_level.add(node.val);
if (node.left != null)
queue.add(node.left);
if(node.right != null)
queue.add(node.right);
}
result.add(current_level);
}
return result;
}
}
- 使用dfs遍历
/**
* 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<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (root == null)
return result;
result = dfs(root, 0, result);
return result;
}
public List<List<Integer>> dfs(TreeNode node, int level, List<List<Integer>> result){
if(node == null)
return result;
if(result.size() < level + 1)
result.add(new ArrayList<Integer>());
result.get(level).add(node.val);
result = dfs(node.left, level+1, result);
result = dfs(node.right, level+1, result);
return result;
}
}
Review
pseudo-code guideline
添加链接描述
- mathematical operations
the allow us to manipulate the values we have stored.
Assignment: ← or :=
Example: c ← 2πr, c := 2πr
Comparison: =, ≠, <, >, ≤, ≥
Arithmetic: +, −, ×, /,
modFloor/ceiling: ⌊, ⌋, ⌈, ⌉
a ← ⌊b⌋ + ⌈c⌉
Logical: and, or
Sums, products: Σ Π
Example: h ← Σa∈A 1/a
- keyword
In pseudocode, they are used to indicate common input-output and processing operations. They are written fully in uppercase.
START: this is the start of your pseudocode
INPUT: this is data retrieved from the user through typing or through an input device
READ/GET: this is input used when reading data from a data file
PRINT, DISPLAY, SHOW: this will show you output to a screen or the relevant output device.
COMPUTE, CALCULATE, DETERMINE: this is used to calculate the result of an expression
SET,INIT: to initialize values
INCREMENT, BUMP: to increase the value of a variable
DECREMENT: to reduce the value of a variable
- conditionals
during algorithm development, we need statement which evaluate expressions and execute instructions depending on whether the expression evaluated to True or False.
IF - ELSE - IF - ELSE
1.
IF you are happy
THEN smile
ENDIF
2.
IF you are happy THEN
smile
ELSE
frown
ENDIF
3.
IF you are happy THEN
smile
ELSE IF you are sad
frown
ELSE
keep face plain
ENDIF
CASE
INPUT color
CASE color of
red: PRINT “red”
green: PRINT “green”
blue: PRINT “blue”
OTHERS (optional)
PRINT “Please enter a value color”
ENDCASE
- iteration
FOR
FOR every month in a year
Compute number of days
ENDFOR
WHILE
PRECONDITION: variable X is equal to 1
WHILE Population < Limit
Compute Population as Population + Births - Deaths
ENDWHILE
- functions
Function clear monitor
Pass In: nothing
Direct the operating system to clear the monitor
Pass Out: nothing
Endfunction
to emulate a function call in pseudocode, we can use the Call keyword
call: clear monitor
- program wrapping
after writing several functions in our pseudocode, we find the need to wrap everything into one container. This is to improve readability and make the execution flow easier to understand.
to do this, we wrap our code as a program. A program can be defined as a set of instructions that performs a specific task when executed.
PROGRAM makeacupoftea
END
- exception handling
an exception is an event which occurs during program execution that disrupts the normal flow of the instructions. These are events that are non-desirable.
BEGIN
statements
EXCEPTION
WHEN exception type
statements to handle exception
WHEN another exception type
statements to handle exception
END
- conclusion
there are no technical rules for pseudocode, it is meant to be human readable and still convey meaning and flow.
添加链接描述
In general, the vocabulary used in the pseudocode should be the vocabulary of the problem domain, not of the implementation domain.
Extract the next word from the line (good)
set word to get next token (poor)
Append the file extension to the name (good)
name = name + extension (poor)
FOR all the characters in the name (good)
FOR character = first to last (ok)
Note that the logic must be decomposed to the level of a single loop or decision.
The “structured” part of pseudocode is a notation for representing six specific structured programming constructs: SEQUENCE, WHILE, IF-THEN-ELSE, REPEAT-UNTIL, FOR, and CASE. Each of these constructs can be embedded inside any other construct. These constructs represent the logic, or flow of control in an algorithm.
- SEQUENCE
sequential control is indicated by writing one action after another, each action on a line by itself, and all actions aligned with the same indent. The actions are preformed in the sequence that they are written.
Example
Brush teeth
Wash face
Comb hair
Smile in mirror
Common Action Keywords
Input: READ, OBTAIN, GET
Output: PRINT, DISPLAY, SHOW
Compute: COMPUTE, CALCULATE, DETERMINE
Initialize: SET, INIT
Add one: INCREMENT, BUMP
- IF - THEN - ELSE
IF condition THEN
sequence 1
ELSE
sequence 2
ENDIF
- WHILE
WHILE condition
sequence
ENDWHILE
- CASE
A CASE construct indicates a multiway branch based on conditions that are mutually exclusive. Four keywords, CASE, OF, OTHERS, and ENDCASE, and conditions are used to indicate the various alternative. The general form is:
CASE expression OF
condition 1: sequence 1
condition 2: sequence 2
…
condition n: sequence n
OTHERS:
default sequence
END CASE
the OTHERS clause with its default sequence is optional. Conditions are normally numbers of characters.
- REPEAT - UNTIL
this loop is similar to the WHILE loop except that the test is performed at the bottom of the loop instead of at the top.
REPEAT
sequence
UNTIL condition
- FOR
this loop is a specialized construct for iterating a specific number of times, often called a “counting” loop.
FOR iteration bounds
sequence
ENDFOR
- NESTED CONSTRUCTS
the constructs can be embedded within each other, and this is made clear by use of indenting. Nested constructs should be clearly indented from their surrounding constructs.
SET total to zero
REPEAT
READ Temperature
IF Temperature > Freezing THEN
INCREMENT total
END IF
UNTIL Temperature < zero
Print total
- INVOKING SUBPROCEDURES
use the CALL keyword
CALL AvgAge with StudentAges
CALL Swap with CurrentItem and TargetItem
- EXCEPTION HANDLING
BEGIN
statements
EXCEPTION
WHEN exception type
statements to handle exception
WHEN another exception type
statements to handle exception
END
"Adequate"
FOR X = 1 to 10
FOR Y = 1 to 10
IF gameBoard[X][Y] = 0
Do nothing
ELSE
CALL theCall(X, Y) (recursive method)
increment counter
END IF
END FOR
END FOR
"Better"
Set moveCount to 1
FOR each row on the board
FOR each column on the board
IF gameBoard position (row, column) is occupied THEN
CALL findAdjacentTiles with row, column
INCREMENT moveCount
END IF
END FOR
END FOR
(Note: the logic is restructured to omit the "do nothing" clause)
"Not So Good"
FOR all the number at the back of the array
SET Temp equal the addition of each number
IF > 9 THEN
get the remainder of the number divided by 10 to that index
and carry the "1"
Decrement one
Do it again for numbers before the decimal
"Good Enough (not perfect)"
SET Carry to 0
FOR each DigitPosition in Number from least significant to most significant
COMPUTE Total as sum of FirstNum[DigitPosition] and SecondNum[DigitPosition] and Carry
IF Total > 10 THEN
SET Carry to 1
SUBTRACT 10 from Total
ELSE
SET Carry to 0
END IF
STORE Total in Result[DigitPosition]
END LOOP
IF Carry = 1 THEN
RAISE Overflow exception
END IF
Tip
如何阅读别人的代码:
从上往下阅读。先关注function,再关注function的内容。
func1()
func2()
func3()
share
如何画流程图
添加链接描述