leetcode 094 —— Binary Tree Inorder Traversal

来源:互联网 发布:数据库原理试题 编辑:程序博客网 时间:2024/06/16 00:56

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].


方法一:递归,时间0ms

class Solution {public:vector<int> inorderTraversal(TreeNode* root) {vector<int> res;dfs(root, res);return res;}void dfs(TreeNode* root, vector<int> &res){if (!root)return;res.push_back(root->val);dfs(root->left,res);dfs(root->right, res);}};


方法二:栈,时间4ms

class Solution {public:vector<int> inorderTraversal(TreeNode* root) {vector<int> res;if (!root) return res;TreeNode *p = root;stack<TreeNode*> stk;while (p || !stk.empty()){while (p){stk.push(p);p = p->left;}p = stk.top();res.push_back(p->val);stk.pop();p = p->right;}return res;}};


0 0
原创粉丝点击