每一个遍历都用了两种方法,recursive(递归)和iteratively(用栈)
Leetcode94:Binary Tree Inorder Traversal
题目描述
Given a binary tree, return the inorder traversal of its nodes’ values.
Example:
Input: [1,null,2,3]
1 | 1 |
Output: [1,3,2]
Follow up: Recursive solution is trivial, could you do it iteratively?
解
python code[20ms 11.7MB]
用递归
1 | # Definition for a binary tree node. |
c++ code[0ms 8.7MB]
用栈,一开始的做法改node了,因为不然会死循环,虽然这个右节点的左节点被访问过了,但是没有record,下次还会再访问,所以就把访问过的左节点改成空。狠毒如我。
1 | /** |
不改node的做法呢,是在每次while开头访问top的时候,让这个top的所有左节点都已经被访问过了。
1 | /** |
Leetcode144:Binary Tree Preorder Traversal
题目描述
Given a binary tree, return the preorder traversal of its nodes’ values.
Example:
Input: [1,null,2,3]
1 | 1 |
Output: [1,2,3]
Follow up: Recursive solution is trivial, could you do it iteratively?
解
python code[16ms 11.9MB]
用递归,python用递归解决这种是真的方便又简洁啊
1 | # Definition for a binary tree node. |
c++ code[4ms 9.2MB]
前序比较简单咯,碰见了就直接push back就行了
1 | /** |
Leetcode145:Binary Tree Postorder Traversal
题目描述
Given a binary tree, return the postorder traversal of its nodes’ values.
Example:
Input: [1,null,2,3]
1 | 1 |
Output: [3,2,1]
Follow up: Recursive solution is trivial, could you do it iteratively?
解
python code[28ms 11.8MB]
递归
1 | # Definition for a binary tree node. |
c++ code[4ms 9.1MB]
和中序差不多,但是在把当前root->val放进result之前要判断一下root->right是否访问过
1 | /** |