前序遍历(递归、非递归)

递归:

 1 package 剑指offer.前序遍历;
 2 
 3 import java.util.ArrayList;
 4 
 5 /**
 6  * Created by nick on 2018/10/6.
 7  */
 8 public class Solution {
 9     ArrayList<Integer> res=new ArrayList<Integer>();
10     public void preNode(TreeNode root){
11         if(root==null)
12             return;
13         res.add(root.val);
14         preNode(root.left);
15         preNode(root.right);
16     }
17     
18 }
19 class TreeNode {
20     int val = 0;
21     TreeNode left = null;
22     TreeNode right = null;
23 
24     public TreeNode(int val) {
25         this.val = val;
26 
27     }
28 }

非递归:

 1 package 剑指offer.前序遍历;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Stack;
 5 
 6 /**
 7  * Created by nick on 2018/10/6.
 8  */
 9 public class Solution1 {
10     ArrayList<Integer> res=new ArrayList<Integer>();
11     public ArrayList<Integer> preNode(TreeNode root){
12         Stack<TreeNode> temp=new Stack<TreeNode>();
13         if(root==null)
14             return res;
15         temp.push(root);
16         while (!temp.isEmpty()){
17             TreeNode t=temp.pop();
18             res.add(t.val);
19             if(t.right!=null)
20                 temp.push(root.right);
21             if(t.left!=null)
22                 temp.push(root.left);
23 
24         }
25         return res;
26     }
27 
28     public static void main(String[] args) {
29         TreeNode root=new TreeNode(1);
30         root.left=new TreeNode(2);
31         root.right=new TreeNode(3);
32 
33         System.out.println(new Solution1().preNode(root));
34     }
35 }

猜你喜欢

转载自www.cnblogs.com/nickup/p/9746993.html