-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpreorder.java
More file actions
33 lines (32 loc) · 839 Bytes
/
preorder.java
File metadata and controls
33 lines (32 loc) · 839 Bytes
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;
}