码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode: Binary Tree Preorder Traversal [144]

时间:2014-06-30 06:21:18      阅读:334      评论:0      收藏:0      [点我收藏+]

标签:leetcode   算法   面试   

【题目】

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?


【题意】

    非递归返回先序遍历结果


【思路】

        维护一个栈即可


【代码】

/**
 * 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) {
        vector<int> result;
        stack<TreeNode*> st;
        TreeNode*node=root;
        while(node){
            result.push_back(node->val);
            st.push(node);
            node=node->left;
        }
        while(!st.empty()){
            node=st.top()->right; st.pop();
            while(node){
                result.push_back(node->val);
                st.push(node);
                node=node->left;
            }
        }
        return result;
    }
};


LeetCode: Binary Tree Preorder Traversal [144],布布扣,bubuko.com

LeetCode: Binary Tree Preorder Traversal [144]

标签:leetcode   算法   面试   

原文地址:http://blog.csdn.net/harryhuang1990/article/details/35780357

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!