进阶之路

首页 新随笔 管理

Binary Tree Zigzag Level Order Traversal

Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).

For example: Given binary tree {3,9,20,#,#,15,7},

    3
   / \
  9  20
    /  \
   15   7

 

return its zigzag level order traversal as:

[
  [3],
  [20,9],
  [15,7]
]

思路: 使用两个队列(一个可以顺序读,所以用vector模拟),每个队列放一层结点。

 

Binary Tree Inorder Traversal

OJ: https://oj.leetcode.com/problems/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. 使用栈:  O(n) Time, O(n) Space。 2. Morris traversal (构造线索树), O(n) Time, O(1) Space.

1. 使用栈

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> inorderTraversal(TreeNode *root) {
        vector<int> vec;
        if(root == NULL) return vec;
        TreeNode *p = root;
        stack<TreeNode *> st;
        st.push(p);
        while(p->left) { p = p->left; st.push(p); }
        while(!st.empty()) {
            TreeNode *q = st.top();
            st.pop();
            vec.push_back(q->val);
            if(q->right) {
                q = q->right; st.push(q);
                while(q->left) { q = q->left; st.push(q); }
            }
        }
        return vec;
    }
};

 2. Morris Traversal

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> inorderTraversal(TreeNode *root) {
        vector<int> vec;
        TreeNode *cur, *pre;
        cur = root;
        while(cur) {
            if(cur->left == NULL) {
                vec.push_back(cur->val);
                cur = cur->right;
            } else {
                pre = cur->left;
                while(pre->right && pre->right != cur) pre = pre->right;
                if(pre->right == NULL) {
                    pre->right = cur;
                    cur = cur->left;
                } else {
                    pre->right = NULL;
                    vec.push_back(cur->val);
                    cur = cur->right;
                }
            }
        }
        return vec;
    }
};

 

posted on   进阶之路  阅读(180)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示