zoukankan      html  css  js  c++  java
  • Binary Tree Postorder Traversal

    Link: http://oj.leetcode.com/problems/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].

    Note: Recursive solution is trivial, could you do it iteratively?

    Iterative version:

     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 public class Solution {
    11     public ArrayList<Integer> postorderTraversal(TreeNode root) {
    12         ArrayList<Integer> nodes = new ArrayList<Integer>();
    13         if (root == null)
    14             return nodes;
    15         Stack<TreeNode> stack = new Stack<TreeNode>();
    16         TreeNode node;
    17         stack.push(root);
    18         while (!stack.isEmpty()) {
    19             node = stack.pop();
    20             nodes.add(node.val);
    21             if (node.left != null)
    22                 stack.push(node.left);
    23             if (node.right != null)
    24                 stack.push(node.right);
    25         }
    26         ArrayList<Integer> result = new ArrayList<Integer>();
    27         for (int i = nodes.size() - 1; i >= 0; i--) {
    28             result.add(nodes.get(i));
    29         }
    30         return result;
    31     }
    32 }

    Recursion version:

     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 public class Solution {
    11     
    12    ArrayList<Integer> nodes = new ArrayList<Integer>();
    13 
    14     public ArrayList<Integer> postorderTraversal(TreeNode root) {
    15         postorderTraversal_recursion(root);
    16         return nodes;
    17     }
    18 
    19     public void postorderTraversal_recursion(TreeNode root) {
    20         if (root == null)
    21             return;
    22         postorderTraversal_recursion(root.left);
    23         postorderTraversal_recursion(root.right);
    24         nodes.add(root.val);
    25     }
    26 }
  • 相关阅读:
    DHCP分配ip地址。0.0.0.0与255.255.255.255
    net-snmp配置文件详解
    net-snmp开发中出现“Error opening specified endpoint"" ”的解决方案
    Elasticsearch 学习笔记
    Prometheus 监控报警系统 AlertManager 之邮件告警
    Match All Query
    Elasticsearch postman
    Centos7修改root密码
    ElasticSearch中profile API的使用
    kafka查询某时间段内的消息
  • 原文地址:https://www.cnblogs.com/Altaszzz/p/3705806.html
Copyright © 2011-2022 走看看