zoukankan      html  css  js  c++  java
  • LintCode-68.二叉树的后序遍历

    二叉树的后序遍历

    给出一棵二叉树,返回其节点值的后序遍历。

    样例

    给出一棵二叉树 {1,#,2,3},

    返回 [3,2,1]

    挑战

    你能使用非递归实现么?

    标签

    递归 二叉树 二叉树遍历

    code

    /**
     * Definition of TreeNode:
     * class TreeNode {
     * public:
     *     int val;
     *     TreeNode *left, *right;
     *     TreeNode(int val) {
     *         this->val = val;
     *         this->left = this->right = NULL;
     *     }
     * }
     */
    class Solution {
        /**
         * @param root: The root of binary tree.
         * @return: Postorder in vector which contains node values.
         */
    public:
        vector<int> postorderTraversal(TreeNode *root) {
            // write your code here
            vector<int> order;
            if(root == NULL)
                return order;
    
            stack<TreeNode*> s;
            TreeNode *cur;                      //当前结点 
            TreeNode *pre=NULL;                 //前一次访问的结点 
            s.push(root);
    
            while(!s.empty()) {
                cur=s.top();
                
                //如果当前结点没有孩子结点或者孩子节点都已被访问过 
                if((cur->left==NULL&&cur->right==NULL)|| (pre!=NULL&&(pre==cur->left||pre==cur->right))) {
                    order.push_back(cur->val);
                    s.pop();
                    pre=cur; 
                }
                else {
                    if(cur->right!=NULL)
                        s.push(cur->right);
                    if(cur->left!=NULL)    
                        s.push(cur->left);
                }
            }
            return order;
        }
    };
  • 相关阅读:
    POST
    界面,数据下载
    异步下载
    Cell
    循环&信息添加&颜色修改
    通讯录
    图片循环
    多删搜索
    图片滚动
    TableView
  • 原文地址:https://www.cnblogs.com/libaoquan/p/6807394.html
Copyright © 2011-2022 走看看