zoukankan      html  css  js  c++  java
  • 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?

    分析:这道题与之前那道中序遍历是一样的题型,借助栈stack数据结构。先在stack中push进root,由于是前序遍历,故根结点的访问先于左结点和右结点,因此pop出一个结点,将它的值存入序列中,然后将它的右结点压入栈中,在压入它的左结点(这里为什么要先压入右结点呢?因为左结点要先于右结点访问,但是由于栈是后进先出,故要把左结点后于右结点压入栈中),直至栈为空位置。

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        vector<int> preorderTraversal(TreeNode *root) {
            stack<TreeNode*> StackTree;
            vector<int> data;
            if(root==NULL)
                return data;
            StackTree.push(root);
            while(!StackTree.empty())
            {
                TreeNode *CurrentNode=StackTree.top();
                StackTree.pop();
                data.push_back(CurrentNode->val);
                if(CurrentNode->right!=NULL)
                    StackTree.push(CurrentNode->right);
                if(CurrentNode->left!=NULL)
                    StackTree.push(CurrentNode->left);
            }
            return data;
        }
    };

     递归方法:

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        void Traversal(TreeNode *root,vector<int> &data)
        {
            if(root==NULL)
                return;
            data.push_back(root->val);
            Traversal(root->left,data);
            Traversal(root->right,data);
        }
        vector<int> preorderTraversal(TreeNode *root) {
            vector<int> data;
            Traversal(root,data);
            return data;
        }
    };
  • 相关阅读:
    程序包管理
    磁盘篇
    centos7上常用软件安装
    这个端午
    字节码技术及动态代理
    浅析同步异步阻塞非阻塞
    String拾遗
    Java注解拾遗
    设计模式之总结篇
    设计模式之访问者模式
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3587204.html
Copyright © 2011-2022 走看看