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]
.
Note: Recursive solution is trivial, could you do it iteratively?
/** * 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> result; stack<TreeNode*> st; TreeNode*node=root; while(node){ result.push_back(node->val); st.push(node); node=node->left; } while(!st.empty()){ node=st.top()->right; st.pop(); while(node){ result.push_back(node->val); st.push(node); node=node->left; } } return result; } };
LeetCode: Binary Tree Preorder Traversal [144],布布扣,bubuko.com
LeetCode: Binary Tree Preorder Traversal [144]
原文地址:http://blog.csdn.net/harryhuang1990/article/details/35780357