码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-10-06 13:16:38      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:string   遍历   new   oid   ati   bsp   print   main   col   

递归:

 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 }

 

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

标签:string   遍历   new   oid   ati   bsp   print   main   col   

原文地址:https://www.cnblogs.com/nickup/p/9746993.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!