&LeetCode144& 二叉树的前序遍历

题目

给定一个二叉树,返回它的前序遍历。

示例:
输入: [1,null,2,3]
1

2
/
3

输出: [1,2,3]

来源:力扣(LeetCode

思路

二叉树的中序遍历顺序为左-根-右;
使用栈的解法:
首先,从根节点开始,先将根节点压入栈;
然后,再将其所有右子结点压入栈,然后取出栈顶节点,保存节点值;
其次,再将当前指针移到其左子节点上,若存在左子节点,则在下次循环时又可将其所有左子结点压入栈中。

C++代码

class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) 
    {
        vector<int> res;
        stack<TreeNode*> s;
        TreeNode *p = root;
        while (!s.empty() || p) 
        {
            if (p) 
            {
                s.push(p);
                res.push_back(p->val);
                p = p->left;
            } 
            else 
            {
                TreeNode *t = s.top(); 
                s.pop();
                p = t->right;
            }
        }
        return res;
    }
};
发布了58 篇原创文章 · 获赞 20 · 访问量 2191

猜你喜欢

转载自blog.csdn.net/weixin_40482465/article/details/104519697