Binary Tree Inorder Traversal

Binary Tree Inorder Traversal_第1张图片
Binary Tree Inorder Traversal.png

解題思路 :

  1. post order 的 recursive 解法 left, self, right
  2. 如果要使用 iterative 的做法 可以用 stack 來做 先用 root 檢查 只要有 left child 就一層一層把所有 left child 都放入 stack 然後再拿 top 出來放入 result 之後檢查從 stack 出來的 node 的 right child 是否有左邊子節點 繼續做相同的步驟

C++ code :


//Recursive

class Solution {

/**
 * @param root: The root of binary tree.
 * @return: Inorder in vector which contains node values.
 */

public:

void inOrder(TreeNode *root, vector &res)
{
    if(root == nullptr) return;
    inOrder(root->left, res);
    res.emplace_back(root->val);
    inOrder(root->right, res);
}


vector inorderTraversal(TreeNode *root) {
    // write your code here
    vector res;
    inOrder(root, res);
    return res;
}

};

//Iterative

class Solution {

/**
 * @param root: The root of binary tree.
 * @return: Inorder in vector which contains node values.
 */

public:

vector inorderTraversal(TreeNode *root) {
    // write your code here
    vector res;
    if(root == nullptr) return res;
    stack s;
    TreeNode *cur = root;
    while(cur || !s.empty())
    {
        while(cur)
        {
            s.push(cur);
            cur = cur->left;
        }
        cur = s.top();
        s.pop();
        res.emplace_back(cur->val);
        cur = cur->right;
    }
    return res;
}

};

你可能感兴趣的:(Binary Tree Inorder Traversal)