[LintCode]66.二叉树的前序遍历

xiaoxiao2021-02-28  105

给出一棵二叉树,返回其节点值的前序遍历。

样例

给出一棵二叉树 {1,#,2,3},

1 \ 2 / 3

 返回 [1,2,3].

/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */ class Solution { public: /* * @param root: A Tree * @return: Preorder in ArrayList which contains node values. */ vector<int> preorderTraversal(TreeNode * root) { vector<int> tmp; if(root==NULL) return tmp; stack<TreeNode*> s; s.push(root); while(!s.empty()){ TreeNode* cur=s.top(); tmp.push_back(cur->val); s.pop(); if(cur->right!=NULL) s.push(cur->right); if(cur->left!=NULL) s.push(cur->left); } return tmp; } };

转载请注明原文地址: https://www.6miu.com/read-45221.html

最新回复(0)