1. 程式人生 > >LeetCode(50) Binary Tree Inorder Traversal 中序遍歷

LeetCode(50) Binary Tree Inorder Traversal 中序遍歷

題目描述

Given a binary tree, return the inorder traversal of its nodes’ values.

For example:
Given binary tree {1,#,2,3},

這裡寫圖片描述

return [1,3,2].

解題思路

之前在二叉樹的先序遍歷中已經介紹了二叉樹遍歷的思路了,這裡直接上程式碼。

遞迴解法

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution { public: void traversal(TreeNode* node, vector<int>& node_value) { if(!node) return; traversal(node->left, node_value); node_value.push_back(node->val); traversal(node->right, node_value); } vector<int> inorderTraversal(TreeNode* root) { vector
<int>
node_value; traversal(root, node_value); return node_value; } };

非遞迴解法

/**
 * Definition for a binary tree node.
 * 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> node_value; if(!root) return node_value; stack<TreeNode*> nodes; while(root) { nodes.push(root); root = root->left; } while(!nodes.empty()) { TreeNode* top = nodes.top(); node_value.push_back(top->val); nodes.pop(); top = top->right; while(top) { nodes.push(top); top = top->left; } } return node_value; } };