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]
.
解法一:用栈实现(递归本质)
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> result; 14 stack<TreeNode *> node_stack; 15 if(root!=NULL) 16 node_stack.push(root); 17 TreeNode *node; 18 19 while(!node_stack.empty()) 20 { 21 node=node_stack.top(); 22 result.push_back(node->val); 23 node_stack.pop(); 24 25 if(node->right!=NULL) node_stack.push(node->right); 26 if(node->left!=NULL) node_stack.push(node->left); 27 } 28 29 return result; 30 31 } 32 };
解法二:递归方式
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> result; 14 preorder(root,result); 15 return result; 16 17 18 } 19 void preorder(TreeNode *node,vector<int> &result) 20 { 21 if(node!=NULL) 22 { 23 result.push_back(node->val); 24 preorder(node->left,result); 25 preorder(node->right,result); 26 } 27 28 } 29 };
解法三:morris遍历方式 有待更新。