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]
.
Note: Recursive solution is trivial, could you do it iteratively?
递归解法
对这道题,用递归是最简单的了,具体程序如下:
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> rVec; 14 preorderTraversal(root, rVec); 15 return rVec; 16 } 17 18 void preorderTraversal(TreeNode *tree, vector<int>& rVec) 19 { 20 if(!tree) 21 return; 22 23 rVec.push_back(tree->val); 24 preorderTraversal(tree->left, rVec); 25 preorderTraversal(tree->right, rVec); 26 } 27 };
非递归解法
非递归解法相对就要难很多了,理解起来比较抽象。在这里我们需要借助栈。当左子树遍历完后,需要回溯并遍历右子树。具体程序如下:
1 vector<int> preorderTraversal(TreeNode* root) { 2 vector<int> rVec; 3 stack<TreeNode *> st; 4 TreeNode *tree = root; 5 while(tree || !st.empty()) 6 { 7 if(tree) 8 { 9 st.push(tree); 10 rVec.push_back(tree->val); 11 tree = tree->left; 12 } 13 else 14 { 15 tree = st.top(); 16 st.pop(); 17 tree = tree->right; 18 } 19 } 20 21 return rVec; 22 }
Binary Tree Inorder Traversal
题目要求:
Given a binary tree, return the inorder traversal of its nodes‘ values.
For example:
Given binary tree {1,#,2,3}
,
1 2 / 3
return [1,3,2]
.
Note: Recursive solution is trivial, could you do it iteratively?
这道题的非递归解法跟上题的非递归解法基本一致,只是访问的节点时机不一样,具体程序如下:
1 vector<int> inorderTraversal(TreeNode* root) { 2 vector<int> rVec; 3 stack<TreeNode *> st; 4 TreeNode *tree = root; 5 while(tree || !st.empty()) 6 { 7 if(tree) 8 { 9 st.push(tree); 10 tree = tree->left; 11 } 12 else 13 { 14 tree = st.top(); 15 rVec.push_back(tree->val); 16 st.pop(); 17 tree = tree->right; 18 } 19 } 20 21 return rVec; 22 }
Binary Tree Postorder Traversal
题目要求:
Given a binary tree, return the postorder traversal of its nodes‘ values.
For example:
Given binary tree {1,#,2,3}
,
1 2 / 3
return [3,2,1]
.
Note: Recursive solution is trivial, could you do it iteratively?