1. 程式人生 > >【LeetCode】94. Binary Tree Inorder Traversal(C++)

【LeetCode】94. Binary Tree Inorder Traversal(C++)

地址:https://leetcode.com/problems/binary-tree-inorder-traversal/

題目:

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

Example:
在這裡插入圖片描述

理解:

二叉樹的中序遍歷

遞迴實現:

class Solution {
public:
	vector<int> inorderTraversal(TreeNode* root) {
		vector<int> res;
		InOrder(root,
res); return res; } void InOrder(TreeNode* root, vector<int>& res) { if (!root) return; InOrder(root->left, res); res.push_back(root->val); InOrder(root->right, res); } };

非遞迴實現:

class Solution {
public:
	vector<int> inorderTraversal(TreeNode* root) {
		vector<
int> res; stack<TreeNode*> stk; TreeNode* p = root; while (p || !stk.empty()) { if (p) { stk.push(p); p = p->left; } else { p= stk.top(); stk.pop(); res.push_back(p->val); p = p->right; } } return res; } };

基於線索樹的實現

前面兩種空間複雜度都是 O

( n ) O(n)
基於線索數,可以把空間複雜度變為 O ( 1 ) O(1)

class Solution {
public:
	vector<int> inorderTraversal(TreeNode* root) {
		vector<int> res;
		TreeNode* curr = root;
		while (curr) {
			if (curr->left) {
				TreeNode* pre = curr->left;
				while (pre->right && (pre->right != curr)) {
					pre = pre->right;
				}
				//如果是第一次到達,修改線索樹
				if (!pre->right) {
					pre->right = curr;
					curr = curr->left;
				}
				//第二次到達,改回去
				else {
					pre->right = nullptr;
					res.push_back(curr->val);
					curr = curr->right;
				}
			}
			else {
				res.push_back(curr->val);
				curr = curr->right;
			}
		}
		return res;
	}
};