LeetCode算法题目:Binary Tree Preorder Traversal

来源:互联网 发布:淘宝怎么发货填写单号 编辑:程序博客网 时间:2024/05/30 23:19

题目:

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

For example:

Given binary tree {1,#,2,3},
这里写图片描述
return [1,2,3].


分析:

用迭代的方法实现二叉树的遍历,借助list,stack实现。首先在stack中push入当前的root,由于是前序遍历,故root的value是先于左子树和右子树访问的,故pop取出一个结点,将它的value加入访问序列。之后压入它的右子树和左子树。直到stack为空。


题目:

/** * Definition for a binary tree node. * 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) {        vector<int> res;        list<TreeNode*> nodelist;        if(root==NULL) return res;        nodelist.push_front(root);        while(!nodelist.empty()){            TreeNode *cur=nodelist.front();            res.push_back(cur->val);            nodelist.pop_front();            if(cur->right!=NULL) nodelist.push_front(cur->right);            if(cur->left!=NULL) nodelist.push_front(cur->left);        }        return res;    }};
0 0