Leetcode 94. Binary Tree Inorder Traversal

来源:互联网 发布:知其非所以沽名钓誉矣 编辑:程序博客网 时间:2024/06/05 06:13

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

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

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

s思路:
1. 树的问题,就是绕不开遍历。学好遍历,基本树的问题就不成问题了。遍历有两种方式:一种recuesive,一种iterative.这道题要求用iterative.
2. iterative用stack, inorder 和preorder都可以用stack实现,体会下区别。参考http://blog.csdn.net/xinqrs01/article/details/54858782 中preorder的代码,体会区别!

class Solution {public:    vector<int> inorderTraversal(TreeNode* root) {        //        vector<int> res;        stack<TreeNode*> ss;        TreeNode* p=root;        while(p||!ss.empty()){        //小bug:常常把!ss.empty()写成ss.empty()。        //这还提醒了我,常常把if(a==0)写成if(a=0),符号写错的问题常发生,应多检查是否笔误            while(p){                ss.push(p);                p=p->left;            }            p=ss.top();            ss.pop();            res.push_back(p->val);            p=p->right;        }        return res;    }};
0 0
原创粉丝点击