leetcode:Binary Tree Inorder Traversal
来源:互联网 发布:angularjs http json 编辑:程序博客网 时间:2024/05/16 10:49
Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1 \ 2 / 3
return [1,3,2]
.
Note: Recursive solution is trivial, could you do it iteratively?
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
解题思路:
不用递归的方法完成二叉树的中序遍历,就让人想到Morris二叉树遍历方法:非递归,空间复杂度O(1),时间复杂度O(N),不用栈...
但是实际上Morris方法遍历二叉树也是采用的时间换空间的做法,用Morris方法,树中的每一个节点要被访问两次,第一次先把中序遍历次序的前一个节点(其实就是节点的左子树的最右结点的右指针)指向当前节点,第二次访问才是真正的访问当前节点。第一遍要完成的工作可以用下表表示:(图片来自网络)
代码:
/** * 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) { vector<int> ret; TreeNode *p=NULL; while(root){ if(root->left==NULL){//如果左子树为空,访问当前节点,然后向右子树走 ret.push_back(root->val); root=root->right; } else{//左子树非空 p=root->left; //第一次访问时先走到当前节点的左子树的最右结点 while(p->right&&p->right!=root){ p=p->right; } //如果是第一次到达该节点,那么左子树的最右结点肯定是空,把左子树的最右结点的右指针指向当前节点,然后继续向左走 if(p->right==NULL){ p->right=root; root=root->left; } else{//如果左子树的最右结点非空,那么是第二次到达该节点,访问该节点然后向右走 ret.push_back(root->val); p->right=NULL; root=root->right; } } } return ret; }};
0 0
- LeetCode: Binary Tree Inorder Traversal
- [LeetCode]Binary Tree Inorder Traversal
- LeetCode Binary Tree Inorder Traversal
- [Leetcode] Binary Tree Inorder Traversal
- Leetcode: Binary Tree Inorder Traversal
- LeetCode Binary Tree Inorder Traversal
- LeetCode : Binary Tree Inorder Traversal
- [Leetcode] Binary Tree Inorder Traversal
- 【leetcode】Binary Tree Inorder Traversal
- [LeetCode]Binary Tree Inorder Traversal
- Leetcode: Binary Tree Inorder Traversal
- [leetcode]Binary Tree Inorder Traversal
- LeetCode-Binary Tree Inorder Traversal
- Leetcode Binary Tree Inorder Traversal
- [leetcode] Binary Tree Inorder Traversal
- LeetCode - Binary Tree Inorder Traversal
- [LeetCode] Binary Tree Inorder Traversal
- LeetCode | Binary Tree Inorder Traversal
- 中国(北京)国际智能工业与信息安全技术发展论坛暨2014年中国嵌入式系统年会邀请函
- AndroidManifest.xml配置文件2
- HTTPClient4.3.5的示例
- ubuntu下安装stardict星译王词典
- php-------strlen()和mb_strlen()的区别
- leetcode:Binary Tree Inorder Traversal
- [转]Android 保存activity的状态的说明
- 你到底爱不爱我1
- 你到底爱不爱我2
- WPF程序响应系统休眠唤醒消息
- Android Dialog对话框样式设定-最简单,万能有效方法
- 你到底爱不爱我3
- App Store审核指南中文版
- 如何使用virtualbox打开vmdk(vmware)的硬盘文件