zoukankan      html  css  js  c++  java
  • 树——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 }

     

  • 相关阅读:
    Nginx模块fastcgi_cache的几个注意点
    Nginx的fastcgi_cache
    Nginx Location 语法,与简单配置[转]
    nginx location 匹配顺序
    Amoeba基本配置
    LVS的DR模式配置
    Keepalived安装及初步使用
    HAProxy安装及初步使用
    lvs nginx HAProxy优缺点
    Redis安装及初步使用
  • 原文地址:https://www.cnblogs.com/jiqianqian/p/7388224.html
Copyright © 2011-2022 走看看