zoukankan      html  css  js  c++  java
  • LeetCode144:Binary Tree Preorder Traversal

    题目:

    Given a binary tree, return the preorder traversal of its nodes' values.

    For example:
    Given binary tree {1,#,2,3},

       1
        
         2
        /
       3

    return [1,2,3].

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

    解题思路:

    利用栈实现,很简单的一题,不多说了,直接上代码

    实现代码:

    #include <iostream>
    #include <vector>
    #include <stack>
    using namespace std;
    
    /**
    Given a binary tree, return the preorder  traversal of its nodes' values.
    */
     
    
    struct TreeNode {
         int val;
         TreeNode *left;
         TreeNode *right;    
         TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    };
    
    void addNode(TreeNode* &root, int val)
    {
        if(root == NULL)
        {
            TreeNode *node = new TreeNode(val);
            root = node;
        }
        else if(root->val < val)
        {
            addNode(root->right, val);
        }
        else if(root->val > val)
        {
            addNode(root->left, val);
        }
    }
    
    void printTree(TreeNode *root)
    {
        if(root)
        {
            cout<<root->val<<" ";
            printTree(root->left);
            printTree(root->right);
        }
    }
    
    class Solution {
    public:
        vector<int> preorderTraversal(TreeNode *root) {
            vector<int> ivec;
            if(root)
            {    
                stack<TreeNode *> tstack;
                TreeNode *p = root;            
                while(p || !tstack.empty())
                {
                    while(p)
                    {
                        ivec.push_back(p->val);
                        tstack.push(p);
                        p = p->left;
                    }
                    if(!tstack.empty())
                    {
                        TreeNode *t = tstack.top();
                        tstack.pop();
                        p = t->right;
                    }
                }
                
            }
            return ivec;
                           
        }
    };
    int main(void)
    {
        TreeNode *root = new TreeNode(5);
        addNode(root, 7);
        addNode(root, 3);
        addNode(root, 15);
        addNode(root, 1);
        printTree(root);
        cout<<endl;
        
        Solution solution;
        vector<int> v = solution.preorderTraversal(root);
        vector<int>::iterator iter;
        for(iter = v.begin(); iter != v.end(); ++iter)
            cout<<*iter<<" ";
        cout<<endl;
        
        return 0;
    }
  • 相关阅读:
    flask和tornado的区别
    tornado1
    人脸识别
    ocr:img转成pdf,pdf转成pdf
    flask2
    《个人-GIT使用方法》
    课后作业-阅读任务-阅读笔记
    课后作业-阅读任务-阅读提问
    结对-四则运算生成器-设计文档
    团队-手机备忘录-开发环境搭建过程
  • 原文地址:https://www.cnblogs.com/mickole/p/3670916.html
Copyright © 2011-2022 走看看