树——binary-tree-postorder-traversal(树的前序遍历)

问题:

  Given a binary tree, return the preorder traversal of its nodes' values.

  For example:
  Given binary tree{1,#,2,3},

     1
      \
       2
      /
     3

   return[1,2,3].

 

递归方法:

 1 /**
 2  * Definition for binary tree
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 import java.util.*;
11 public class Solution {
12     public ArrayList<Integer> preorderTraversal(TreeNode root) {
13         ArrayList<Integer> list = new ArrayList<Integer>();
14         if(root==null)
15             return list;
16         preorderTraversal(root, list);
17         return list;
18     }
19     public void preorderTraversal(TreeNode root, ArrayList<Integer> list){
20         if(root==null)
21             return;
22         list.add(root.val);      //先遍历根节点
23         preorderTraversal(root.left, list);    //其次遍历左节点
24         preorderTraversal(root.right, list);    //最后遍历右节点
25     }
26 }

 

非递归方法(利用栈)

  说明,按照“右 - 左 - 根”的顺序进栈,“根 - 左 - 右”的顺序出栈,所有为先序遍历

 1  /**
 2  * Definition for binary tree
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 import java.util.*;
11 public class Solution {
12     public ArrayList<Integer> preorderTraversal(TreeNode root) {
13          ArrayList<Integer> list = new ArrayList<Integer>();
14         if(root==null)
15             return list;
16         Stack<TreeNode> stack = new Stack<TreeNode>();
17         stack.push(root);
18         while(!stack.isEmpty()){
19             TreeNode node = stack.pop();
20             list.add(node.val);
21             if(node.right!=null)
22                 stack.push(node.right);
23             if(node.left!=null)
24                 stack.push(node.left);
25         }
26         return list;
27     }
28 }

 

posted on 2017-08-18 10:00  一个不会coding的girl  阅读(197)  评论(0编辑  收藏  举报

导航