144. Binary Tree Preorder Traversal
阿新 • • 發佈:2018-12-16
Given a binary tree, return the preorder traversal of its nodes' values.
Example:
Input:[1,null,2,3]
1 \ 2 / 3 Output:[1,2,3]
Follow up: Recursive solution is trivial, could you do it iteratively?
二叉樹先序遍歷, 根節點-> 左子樹-> 右子樹。使用一個棧來維護已經訪問過的節點。當節點不為空時,當前節點入棧,輸出節點值,繼續向左子樹遍歷。當root為空,從棧中彈出節點,向右子樹進行遍歷。
/** * Definition for a binary tree node. * 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) { if(root==NULL) return vector<int>(); stack<TreeNode*> nodeStack; vector<int> result; while(!nodeStack.empty() || root != NULL) { while(root) { result.push_back(root->val); nodeStack.push(root); root=root->left; } TreeNode* node = nodeStack.top(); nodeStack.pop(); root = node->right; } return result; } };