遍历二叉树

来源:互联网 发布:汽车编程培训 编辑:程序博客网 时间:2024/05/04 04:11
题目:

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?

答题解析:这题主要是需要我们遍历一次二叉树即可,在这我运用了一个stack以及vector来解决,stack用来存储节点,vector则用来存储节点的值;每一次循环stack都会比vector多存一个左节点或者右节点,而再一次循环就会把它存到vector中,循环结束后,所有节点都会存到vector中,最后返回vector即可。

程序:

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

0 0
原创粉丝点击