您当前的位置: 首页 > 

对方正在debug

暂无认证

  • 6浏览

    0关注

    399博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

二叉树的前序遍历(栈实现)

对方正在debug 发布时间:2020-03-03 14:33:06 ,浏览量:6

题目:https://leetcode-cn.com/problems/binary-tree-preorder-traversal/

/**
 * 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 preorderTraversal(TreeNode* root) {
        /*
        *给定一个二叉树,返回它的 前序 遍历。
        */
        vector res;
        stack st;
        if(root == nullptr) return res;
        st.push(root);
        while(!st.empty()) {
            TreeNode *cur = st.top();
            st.pop();
            res.push_back(cur->val);
            if(cur->right != nullptr) st.push(cur->right);
            if(cur->left != nullptr) st.push(cur->left);
        }
        return res;
    }
};
关注
打赏
1664895754
查看更多评论
立即登录/注册

微信扫码登录

0.0355s