LeetCode: Binary Tree Traversal
题目:树的先序和后序。
后序地址:https://oj.leetcode.com/problems/binary-tree-postorder-traversal/
先序地址:https://oj.leetcode.com/problems/binary-tree-preorder-traversal/
后序算法:利用栈的非递归算法。初始时,先从根节点一直往左走到底,并把相应的元素进栈;在循环里每次都取出栈顶元素,如果该栈顶元素的右子树在上一次已经访问到,则将该元素存入vector中,并且记录下上一次访问的元素,否则,往右走一步,然后在一直往左走到底,并把相应的元素进栈。一直循环,直到栈顶结束。代码:
1 /**
2 * Definition for binary tree
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> postorderTraversal(TreeNode *root) {
13 vector<int> result;
14 if(!root) return result;
15 TreeNode *p = root;
16 stack<TreeNode*> stk;
17 while(p){
18 stk.push(p);
19 p = p->left;
20 }
21 TreeNode *pre = NULL;
22 while(!stk.empty()){
23 p = stk.top();
24 if(!p->right || p->right == pre){
25 pre = p;
26 result.push_back(p->val);
27 stk.pop();
28 }else{
29 p = p->right;
30 while(p){
31 stk.push(p);
32 p = p->left;
33 }
34 }
35 }
36 return result;
37 }
38 };
先序算法:利用栈的非递归算法。初始时,先从根节点一直往左走到底,并且把相应的元素进栈,以及把相应的元素存入vector。在循环里,每次取出栈顶元素,然后出栈一个元素,如果有右子树的话,往右走,然后一直往左走到底,并且把相应的元素进栈,以及把相应的元素存入vector。一直循环,直到栈为空。代码:
1 /**
2 * Definition for binary tree
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 if(!root) return result;
15 stack<TreeNode*> stk;
16 TreeNode *p = root;
17 while(p){
18 result.push_back(p->val);
19 stk.push(p);
20 p = p->left;
21 }
22 while(!stk.empty()){
23 p = stk.top();
24 stk.pop();
25 if(p->right){
26 p = p->right;
27 while(p){
28 result.push_back(p->val);
29 stk.push(p);
30 p = p->left;
31 }
32 }
33
34 }
35 return result;
36 }
37 };