首页 > 代码库 > leetcode Binary Tree Preorder Traversal
leetcode Binary Tree Preorder Traversal
实现前序遍历。可参见中序遍历Binary Tree Inorder Traversal
递归:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: void helper144(TreeNode *root, vector<int> &perm) { if (!root) return; perm.push_back(root -> val); helper144(root -> left, perm); helper144(root -> right, perm); } vector<int> preorderTraversal(TreeNode *root) { vector<int> perm; helper144(root, perm); return perm; }};
非递归:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: vector<int> preorderTraversal(TreeNode *root) { vector<int> perm; stack<TreeNode *> sta; TreeNode *p = root; while(!sta.empty() || p) { while(p) { perm.push_back(p->val); if (p -> right) sta.push(p -> right); p = p -> left; } if (!sta.empty()) { p = sta.top(); sta.pop(); } } return perm; }};
leetcode Binary Tree Preorder Traversal
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。