Sunday, July 26, 2015

LintCode (67) Binary Tree Inorder Traversal

Given a binary tree, return the inorder traversal of its nodes' values.
Have you met this question in a real interview? 
Yes
Example
Given binary tree {1,#,2,3},
   1
    \
     2
    /
   3

return [1,3,2].

Challenge
Can you do it without recursion?

真心败给这题了。。。真心只能靠背过了。。。。lol。。。再总结一下吧,希望下次碰到至少能知道。。。

模拟这个例子的思路的话,一路向左,一边向左一边push当前的位置, 1 -> stk. 
直到当前为Null, 1->null, 那么不能push到stk, 则回溯pop stack,打印当前结果, 去忘 stk.top()->right, 一路向左。。。

真正的inorder:
inorder(left)
cur
inorder(right)...

老感觉还是有一定理解上的距离的。。。。

不过之所以要先做这题是因为后面的iterator要用到它。。。



 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
36
/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: Inorder in vector which contains node values.
     */
public:
    vector<int> inorderTraversal(TreeNode *root) {
        // write your code here
        vector<int> result;
        stack<TreeNode*> stk;
        while(root || !stk.empty()){
            if (root){
                stk.push(root);
                root = root->left;
            } else{
                root=stk.top();
                stk.pop();
                result.push_back(root->val);
                root=root->right;
            }
        }
        return result;
    }
};

No comments:

Post a Comment