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

问题

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

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

     1
      \
       2
      /
     3

  return[3,2,1].

递归方法

 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> postorderTraversal(TreeNode root) {
13         ArrayList<Integer> list = new ArrayList<Integer>();
14         if(root==null)
15             return list;
16         postorderTraversal(root, list);
17         return list;
18     }
19     public void postorderTraversal(TreeNode root, ArrayList<Integer> list){
20         if(root==null)
21             return;
22         
23         if(root.left!=null)      
24             postorderTraversal(root.left, list);   //先遍历左节点
25         if(root.right!=null)
26             postorderTraversal(root.right, list);   //再遍历右节点
27      list.add(root.val);    //最后遍历根节点
28 }
29 }

非递归方法(利用栈)

 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> postorderTraversal(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<TreeNode> st = new Stack<TreeNode>();
18         stack.push(root);
19         while(!stack.isEmpty()){
20             TreeNode node = stack.pop();
21             if(node.left!=null)
22                 stack.push(node.left);
23             if(node.right!=null)
24                 stack.push(node.right);
25             st.push(node);
26         }
27         while(!st.isEmpty()){
28             list.add(st.pop().val);
29         }
30         return list;
31     }
32     
33 }

 

 

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

导航