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

Appearance settings

Latest commit

 

History

History
History
33 lines (32 loc) · 839 Bytes

File metadata and controls

33 lines (32 loc) · 839 Bytes
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
//二叉树的先序递归
ArrayList<Integer> list =new ArrayList<Integer>();
//先序递归遍历
public ArrayList<Integer> preorderTraversal(TreeNode root) {
if(root!=null){
list.add(root.val);
preorderTraversal(root.left);
preorderTraversal(root.right);
}
return list;
}
// 先序非递归遍历
public ArrayList<Integer> preorderTraversal(TreeNode root)
{
Stack<TreeNode> stack=new Stack<TreeNode>();
stack.push(root);
ArrayList<Integer> list=new ArrayList<Integer>();
while(!stack.isEmpty())
{
ListNode ln = stack.pop();
list.add(ln.val);
if(ln.right!=null)
{
stack.push(ln.right);//先push到栈里面的后弹出,所以先序遍历要先push右子树节点
}
if(ln.left!=null)
{
stack.push(ln.left);
}
}
return list;
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.