此题用递归做比较容易,然后根据前中后的遍历特点:
前序是根左右,
中序是左根右,
后序是左右根。
前序遍历:做题入口
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
if(root == null) return list;
list.add(root.val); //先加入根节点
list.addAll(preorderTraversal(root.left)); //再加入所有的左节点
list.addAll(preorderTraversal(root.right)); //再加入所有的右节点
return list;
}
}
中序遍历:做题入口
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
if(root == null) return list;
List<Integer> leftTree = inorderTraversal(root.left);
list.addAll(leftTree); //左
list.add(root.val); //根
List<Integer> rightTree = inorderTraversal(root.right);
list.addAll(rightTree); //右
return list;
}
}
后序遍历:做题入口
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
if(root == null) return list;
list.addAll( postorderTraversal(root.left));//左
list.addAll(postorderTraversal(root.right)); //右
list.add(root.val); //根
return list;
}
}
题目比较简单,看似三个题目,其实代码就是是顺序不一样,总体来说挺简单。
后序遍历:做题入口
非递归+队列
//进阶版的
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> ret = new LinkedList<>();
Queue<TreeNode> queue = new LinkedList<>(); //队列
if(root!=null) queue.offer(root);
while(!queue.isEmpty()) {
int size = queue.size(); //计算每一层的节点
List<Integer> tmp = new LinkedList<>(); //存储每一层的节点的值
while(size!=0) {
TreeNode cur = queue.poll();
tmp.add(cur.val);
if(cur.left!=null) queue.offer(cur.left); //不为null时添加
if(cur.right!=null) queue.offer(cur.right);
size--;
}
ret.add(tmp);
}
return ret;
}
}
二叉树的最近公共祖先 :做题入口
两种做法
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
//第一种
/*
if(root == null) return null;
if(root == p || root == q) return root;
TreeNode leftTree = lowestCommonAncestor(root.left,p,q);
TreeNode rightTree = lowestCommonAncestor(root.right,p,q);
if(leftTree!=null && rightTree!=null) return root;
else if(leftTree!=null) return leftTree;
else return rightTree;
*/
//第二种 链表公共节点 栈
Stack<TreeNode> stackP = new Stack();
Stack<TreeNode> stackQ = new Stack();
getPath(root,p,stackP);
getPath(root,q,stackQ);
int sizeP = stackP.size();
int sizeQ = stackQ.size();
if(sizeP>sizeQ) {
int tmp = sizeP-sizeQ;
while(tmp!=0){
stackP.pop();
tmp--;
}
}else{
int tmp = sizeQ-sizeP;
while(tmp!=0){
stackQ.pop();
tmp--;
}
}
while(!stackP.isEmpty() && !stackQ.isEmpty()) {
TreeNode p1 = stackP.pop();
TreeNode p2 = stackQ.pop();
if(p1.val== p2.val) return p1;
}
return null;
}
private boolean getPath (TreeNode root,TreeNode node ,Stack<TreeNode> stack){
if(root == null) return false;
stack.push(root);
if(root == node) return true;
boolean b1 = getPath(root.left,node,stack);
if(b1 == true) return true;
boolean b2 = getPath(root.right,node,stack);
if(b2 == true) return true;
if( b1==false && b2==false ) stack.pop();
return false;
}
}