94. Binary Tree Inorder Traversal
Given a binary tree, return the inorder traversal of its nodes’ values.
For example:
Given binary tree [1,null,2,3],return [1,3,2].
Note: Recursive solution is trivial, could you do it iteratively?
这次按照一个类型直接做三道题,分别是 inorder,preoder,postorder
前两题是 medium 难度,postorder 是 hard 难度
所谓的 inorder,就是要求根节点在左节点遍历完成后才会被访问到,于是我们需要首先走到最左的节点。
实话说,树的题目不画张图,经常容易想不清楚,很多细节的边界条件需要考虑到,当我做第二次本以为志在意得的时候,竟然又卡了好一会儿。
在这里主要注意到使用 stack 不要将 null 存入 stack 中,否则将造成问题
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList();
if(root== null){
return res;
}
Stack<TreeNode> st = new Stack();
st.push(root);
TreeNode cur = root;
while(!st.isEmpty() ){
while(cur != null){
cur= cur.left;
if(cur != null){
st.push(cur);
}
}
TreeNode temp = st.pop();
res.add(temp.val);
cur = temp.right;
if(cur != null){
st.push(cur);
}
}
return res;
}
}
144. Binary Tree Preorder Traversal
Given a binary tree, return the preorder traversal of its nodes’ values.
For example:
Given binary tree {1,#,2,3},return [1,2,3].
Preorder 就要求我们每次访问到一个节点就先把那个节点的数字加入到结果中,我们还是使用 stack 来存储。注意到因为左边优先于右边,所以应该先把右边节点压入 stack 再把左边压入。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new LinkedList<>();
if(root==null){
return res;
}
if((root.left==null&&root.right==null)){
res.add(root.val);
return res;
}
Stack<TreeNode> st = new Stack<TreeNode>();
st.push(root);
while(!st.empty()){
TreeNode node = st.pop();
res.add(node.val);
if(node.right!=null){
st.push(node.right);
}
if(node.left!=null){
st.push(node.left);
}
}
return res;
}
}
145. Binary Tree Postorder Traversal
虽然说是 hard,但是在难度并不算太大。
需要注意需要走到最左边的节点然后开始向上遍历。
public class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new LinkedList<>();
if(root==null){
return res;
}
if((root.left==null&&root.right==null)){
res.add(root.val);
return res;
}
Stack<TreeNode> st = new Stack<TreeNode>();
st.push(root);
while(!st.isEmpty()){
TreeNode node = st.pop();
if(node != null){
//reverse the order in res
res.add(0,node.val);
st.push(node.left);
st.push(node.right);
}
}
return res;
}
}