Binary Tree Inorder Traversal

来源:互联网 发布:java试题库及答案 编辑:程序博客网 时间:2024/06/06 00:49

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?

Subscribe to see which companies asked this question.


关于树的遍历,最简单的方法就是使用递归,如果不使用递归的话,就可以借助栈结构来进行回溯。

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


0 0