[leetcode-94]Binary Tree Inorder Traversal(c++)

来源:互联网 发布:仓库管理java源码下载 编辑:程序博客网 时间:2024/04/30 22:31

问题描述:

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

For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [1,3,2].

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

分析:这道题用递归的方法是很容易实现的,代码1给出了递归的做法。但是题目要求用迭代的方法实现。那很自然的使用stack来模拟递归方法的实现。
这道题我实现的时候遇到了问题,我实现的时候没有使用临时变量P,而是使用stack.top(),这样就带来了问题,导致总会去重复执行某代码。导致死循环。之所以会出现这种情况,是没有能把中间部分的元素出栈。

代码1:0ms(递归)

/** * 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:   void inorder(TreeNode* root, vector<int>& res) {        if (!root)            return;        inorder(root->left, res);        res.push_back(root->val);        inorder(root->right, res);    }    vector<int> inorderTraversal(TreeNode* root) {        vector<int> res;        inorder(root,res);        return res;    }};

代码2:0ms(非递归)

/** * 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> inorderTraversal(TreeNode* root) {        stack<TreeNode *> stack;        vector<int> res;        TreeNode* p = root;        while (p || !stack.empty())        {            if (p) {                stack.push(p);                p = p->left;            }            else {                p = stack.top();                stack.pop();                res.push_back(p->val);                p = p->right;            }        }        return res;    }};
0 0
原创粉丝点击