Binary Tree Preorder Traversal
2018-04-01 18:25
323 查看
Given a binary tree, return the preorder traversal of its nodes' values.
Example
Given:
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
if(root==NULL)
return res;
stack<TreeNode*> s;
s.push(root);
while(!s.empty()){
TreeNode *t=s.top();
s.pop();
v.push_back(t->val);
if(t->right) //因为栈是先进后出,所以先放入右结点
s.push(t->right);
if(t->left)
s.push(t->left);
}
return res;
}
};
Example
Given:
1 / \ 2 3 / \ 4 5return
[1,2,4,5,3].class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
if(root==NULL)
return res;
stack<TreeNode*> s;
s.push(root);
while(!s.empty()){
TreeNode *t=s.top();
s.pop();
v.push_back(t->val);
if(t->right) //因为栈是先进后出,所以先放入右结点
s.push(t->right);
if(t->left)
s.push(t->left);
}
return res;
}
};
相关文章推荐
- LeetCode刷题(C++)——Construct Binary Tree from Preorder and Inorder Traversal(Normal)
- LeetCode - Binary Tree Preorder Traversal
- leetcode---Binary Tree Preorder Traversal
- LeetCode(144)Binary Tree Preorder Traversal
- CODE 28: Construct Binary Tree from Preorder and Inorder Traversal
- Simple implementation of the BinaryTree preorder traversal, inorder traversal, post traversal
- LeetCode:Construct Binary Tree from Preorder and Inorder Traversal
- 【leetcode】Construct Binary Tree from Preorder and Inorder Traversal
- Construct Binary Tree from Preorder and Inorder Traversal
- Binary Tree Preorder Traversal
- 【LeetCode】-Construct Binary Tree from Preorder and Inorder Traversal
- 剑指offer 面试题6:重建二叉树(Leetcode105. Construct Binary Tree from Preorder and Inorder Traversal) 解题报告
- [Leetcode] Binary Tree Preorder Traversal
- 【leetcode】Binary Tree Preorder Traversal
- 【LeetCode】105. Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode---Binary Tree Preorder Traversal
- Construct Binary Tree from Preorder and Inorder Traversal
- 144. Binary Tree Preorder Traversal
- Lintcode73 Construct Binary Tree from Preorder and Inorder Traversal solution 题解
- Construct Binary Tree from Preorder and Inorder Traversal-先序和中序构造树