LeetCode 144. Binary Tree Preorder Traversal
前序遍历
递归:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<int> res; 13 void help(TreeNode* root){ 14 // if(!root) return; 15 res.push_back(root->val); 16 if(root->left) help(root->left); 17 if(root->right) help(root->right); 18 } 19 vector<int> preorderTraversal(TreeNode* root) { 20 if(!root) return res; 21 help(root); 22 return res; 23 } 24 25 26 };
迭代:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<int> preorderTraversal(TreeNode* root){ 13 vector<int> res; 14 if(!root) return res; 15 stack<TreeNode*> stk; 16 stk.push(root); 17 18 while(!stk.empty()){ 19 TreeNode* cur = stk.top(); 20 stk.pop(); 21 res.push_back(cur->val); 22 23 if(cur->right) stk.push(cur->right); 24 if(cur->left) stk.push(cur->left); 25 26 } 27 return res; 28 } 29 30 };
stk存放待处理节点的倒序,即top为最先处理的节点。
每次处理完top后,将top的右、左儿子依次push进stk中,所以下一次先处理的是top的左儿子(再深一步想也即先处理top的左子树,在该子树中优先处理其中的左子树,以此类推),符合前序遍历的规则。
另有算法未看,留坑。