非递归无栈无父节点中序遍历二叉树

好东东。灵感来源于线索二叉树


/**
 * 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) {
        TreeNode* prev = NULL;
		TreeNode* cur = root;
		vector<int> ans;
		if(root == NULL) {
			return ans;
		}
		while(cur) {
			if(cur->left == NULL) {
				ans.push_back(cur->val);
				cur = cur->right;
			} else {
				prev = cur->left;
				while(prev->right != NULL && prev->right != cur) {
					prev = prev->right;
				}
				if(prev->right == NULL) {
					prev->right = cur;
					cur = cur->left;
				} else {
					prev->right = NULL;
					ans.push_back(cur->val);
					cur = cur->right;
				}
			}
		}

		return ans;
    }
};



Preorder:

#include <stdio.h>
#include <vector>

using namespace std;

 // Definition for binary tree
 struct TreeNode {
     int val;
	 TreeNode *left;
     TreeNode *right;
     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 };

 class Solution {
	 public:
	 void visit(TreeNode* cur) {
		 if(cur != NULL) {
			printf("%d\n",cur->val);
		 }
	 }
	 void preOrderTravelBT(TreeNode* root) {
		 TreeNode* cur = root;
		 TreeNode* pre = NULL;
		 if(root == NULL) {
			 return;
		 }
		 while(cur) {
			 if(cur->left == NULL) {
				 visit(cur);
				 cur = cur->right;
			 } else {
				 pre = cur->left;
				 while(pre->right != NULL && pre->right != cur) {
					 pre = pre->right;
				 }
				 if(pre->right == NULL) {
					 pre->right = cur;
					 visit(cur);
					 cur = cur->left;
				 } else {
					 pre->right = NULL;
					 cur = cur->right;
				 }
			 }
		 }
	 }
 };

int main(int argc, char *argv[])
{
	Solution s;
	TreeNode* t9 = new TreeNode(9);
	TreeNode* t7 = new TreeNode(7);
	t7->left = t9;
	TreeNode* t8 = new TreeNode(8);
	TreeNode* t6 = new TreeNode(6);
	t6->right = t7;
	TreeNode* t5 = new TreeNode(5);
	t5->left = t8;
	TreeNode* t4 = new TreeNode(4);
	TreeNode* t3 = new TreeNode(3);
	t3->right = t6;
	TreeNode* t2 = new TreeNode(2);
	t2->left = t4;
	t2->right = t5;
	TreeNode* t1 = new TreeNode(1);
	t1->left = t2;
	t1->right = t3;

	TreeNode* t10 = new TreeNode(10);
	t8->right = t10;

	s.preOrderTravelBT(t1);
	
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值