欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

1.二叉树的中序遍历

发布时间:2025/6/15 编程问答 45 豆豆
生活随笔 收集整理的这篇文章主要介绍了 1.二叉树的中序遍历 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

题目:给出一棵二叉树,返回其中序遍历

 

/**

 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: Inorder in vector which contains node values.
     */
public:
    vector<int> inorderTraversal(TreeNode *root) {
        // write your code here
        vector<TreeNode *> t;
        vector<int> res;
while(root != NULL || t.size() != 0) {
while(root != NULL) {
                t.push_back(root);
                root = root->left;
            }
            root = t.back();
            t.pop_back();
            res.push_back(root->val);
            root = root->right;
        }
        return res;
    }
};

转载于:https://www.cnblogs.com/ALIMAI2002/p/7206740.html

总结

以上是生活随笔为你收集整理的1.二叉树的中序遍历的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。