zoukankan      html  css  js  c++  java
  • [容易]二叉树的后序遍历

    题目来源:http://www.lintcode.com/zh-cn/problem/binary-tree-postorder-traversal/#

    C++版 VS2012测试通过

     1 //#include <iostream>
     2 //#include <vector>
     3 //using namespace std;
     4 
     5 //Definition of TreeNode
     6 //class TreeNode {
     7 //public:
     8 //    int val;
     9 //    TreeNode *left, *right;
    10 //    TreeNode(int val=-1) {
    11 //        this->val = val;
    12 //        this->left = this->right = NULL;
    13 //    }
    14 //};
    15 
    16 //输入前序遍历,创建二叉树
    17 //举例输入ABDH#K###E##CFI###G#J##
    18 //void CreateBiTree(TreeNode **T)//*T是指向BiTNode的指针
    19 //{
    20 //    *T=new TreeNode;
    21 //    if(*T==NULL)//如果*T还是指向NULL,表示内存分配失败,退出程序
    22 //        exit(OVERFLOW);
    23 //    char ch;
    24 //    cin>>ch;
    25 //    if(ch=='#')
    26 //        *T=NULL;
    27 //    else
    28 //    {
    29 //        CreateBiTree(&((*T)->left));//创建&(*T)->lchild临时变量,传入CreateBiTree,构造左子树
    30 //        CreateBiTree(&((*T)->right));//创建&(*T)->rchild临时变量,传入CreateBiTree,构造右子树
    31 //        (*T)->val=ch;//*T指向的节点的data分配内容,即生成根节点
    32 //    }
    33 //}
    34 
    35 class Solution {
    36 public:
    37     /**
    38      * @param root: The root of binary tree.
    39      * @return: Preorder in vector which contains node values.
    40      */
    41     vector<int> preorder;
    42     void traverse(TreeNode *root) {
    43         if (root == NULL) {
    44             return;
    45         }
    46         traverse(root->left);
    47         traverse(root->right);
    48         preorder.push_back(root->val);
    49     }
    50     vector<int> postorderTraversal(TreeNode *root) {
    51          //write your code here
    52         preorder.clear();
    53         traverse(root);
    54         return preorder;
    55     }
    56 };
    57 
    58 //测试
    59 //int main()
    60 //{
    61 //    Solution s;
    62 //    vector<int> preorder;
    63 //
    64 //    TreeNode **pp;//定义指向BiTNode的二级指针pp
    65 //    TreeNode *p;//定义指向BiTNode的指针p
    66 //    pp=&p;//pp指向p
    67 //    p=NULL;//初始化p指向NULL
    68 //    CreateBiTree(pp);//传入指向p的地址,创建二叉树
    69 //    
    70 //    preorder=s.postorderTraversal(p);//传入指向BiTNode的地址,前序遍历创建好的二叉树
    71 //    for(int i=0;i<preorder.size();i++)
    72 //        putchar(preorder.at(i));
    73 //}
  • 相关阅读:
    线程基础知识归纳
    并发编程情况下几个相应问题简介
    Spring Security的RBAC数据模型嵌入
    Mysql插入中文的字段内容时乱码的解决方法
    部分排序算法总结
    sendEmail 阿里云使用587端口
    linux服务器关闭ipv6 方法
    centos 6.8 安装git 报错
    强大的xargs
    nfs环境搭建报错clnt_create: RPC: Program not registered
  • 原文地址:https://www.cnblogs.com/hslzju/p/5618394.html
Copyright © 2011-2022 走看看