94、Binary Tree Inorder Traversal

来源:互联网 发布:macbook软件下载网站 编辑:程序博客网 时间:2024/05/19 15:26

题目:

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?

解题思路:

迭代法中序遍历。

python版本:

class Solution(object):    def inorderTraversal(self, root):        """        :type root: TreeNode        :rtype: List[int]        """        def goAlongLeft(x,s):            while(x):                s.append(x)                x = x.left        stack,res = [],[]        x = root        while(True):            goAlongLeft(x,stack)            if(len(stack)==0):break            x = stack.pop()            res.append(x.val)            x = x.right        return res

c++版本:

class Solution {public:    void goAlongLeft(TreeNode *x,stack<TreeNode *>&s){        while(x){            s.push(x);            x = x->left;        }    }    vector<int> inorderTraversal(TreeNode* root) {        TreeNode *x = root;        vector<int> res;        stack<TreeNode *>s;        while(true){            goAlongLeft(x,s);            if(s.empty())break;            x = s.top();s.pop();            res.push_back(x->val);            x = x->right;        }        return res;    }};


0 0
原创粉丝点击