LeetCode--Binary Tree Preorder Traversal
题目:
Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1 \ 2 / 3
return [1,2,3]
.
代码:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */
方法一:先将根节点的右儿子,左儿子读入,再左儿子出栈,其儿子进栈,如此进行...
<span style="white-space:pre"> </span> vector<int> preorderTraversal(TreeNode* root) { vector<int> vec; stack<TreeNode*> stk; if(root != NULL) { stk.push(root); while(!stk.empty()) { root = stk.top(); stk.pop(); vec.push_back(root->val); if(root->right != NULL) stk.push(root->right); if(root->left != NULL) stk.push(root->left); } } return vec; }
方法二:先读取所有左节点,在自底向上读取右节点。
<span style="white-space:pre"> </span> vector<int> preorderTraversal(TreeNode* root) { vector<int> vec; stack<TreeNode*> stk; while(root != NULL || !stk.empty()) { if(root) { while(root) { vec.push_back(root->val); stk.push(root); root = root->left; } } else { root = stk.top()->right; stk.pop(); } } return vec; }