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].

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

    递归方法

     1 /**
     2  * Definition for binary tree
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     vector<int> postorderTraversal(TreeNode *root) {
    13         if(root==NULL)
    14             return v;
    15         TreeNode *left=root->left,*right=root->right;
    16         postorderTraversal(left);
    17         postorderTraversal(right);
    18         v.push_back(root->val);
    19         return v;
    20     }
    21     
    22     
    23     vector<int> v;
    24 };

    非递归

    处理并出栈时判断,该节点是否有子节点或其子节点是否被访问过。并记录上次处理的节点。

     1 /**
     2  * Definition for binary tree
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     vector<int> postorderTraversal(TreeNode *root) {
    13         vector<int> v;
    14         if(root==NULL)
    15             return v;
    16         stack<TreeNode *> tree;
    17         tree.push(root);
    18         TreeNode *pre=NULL;
    19         while(!tree.empty()){
    20             TreeNode *p = tree.top();
    21             if((p->left==NULL&&p->right==NULL)||(pre!=NULL&&(p->left==pre||p->right==pre))){
    22                 v.push_back(p->val);
    23                 pre=p;
    24                 tree.pop();
    25             }else{
    26                 if(p->right!=NULL)
    27                     tree.push(p->right);
    28                 if(p->left!=NULL)
    29                     tree.push(p->left);
    30             }
    31         }
    32         return v;
    33     }
    34 };
  • 相关阅读:
    AC自动机---病毒侵袭
    线段树或树状数组---Flowers
    AC自动机---Keywords Search
    AC自动机基础知识讲解
    线段树---Atlantis
    状态压缩DP---Hie with the Pie
    状态压缩DP--Mondriaan's Dream
    【PAT-并查集-水题】L2-007-家庭房产
    【PAT-一道看着很难的水题】L2-023. 图着色问题
    【二叉搜索树】PAT-天梯赛- L2-004. 这是二叉搜索树吗?
  • 原文地址:https://www.cnblogs.com/zl1991/p/6957919.html
Copyright © 2011-2022 走看看