112.路径总和
和求最大路径类似,但是要判断是不是叶子节点。我想的是递归嘛,跑到最下面,如果叶子节点的值和target的值相等就说明满足题目要求就返回true,否则就归到root为空的情况返回false。
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
if(root == null) return false;
if(targetSum == root.val && root.left == null && root.right == null) return true;
return hasPathSum(root.left,targetSum - root.val)
|| hasPathSum(root.right,targetSum - root.val);
}
}
94.二叉树的中序遍历
递归
递归遍历简单啊
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList();
inorder(list,root);
return list;
}
public void inorder(List<Integer> list,TreeNode node){
if(node == null) return ;
inorder(list,node.left);
list.add(node.val);
inorder(list,node.right);
}
}
先添加左节点,添加根,最后添加右节点。递归方法的前中后序只是改变添加根节点的位置,后面就不写递归方法了。
迭代
迭代就先把向左的节点全推入栈,出栈添加值,然后判断一下有没有右节点,右节点有没有左右节点有就再跑到最左边。以此类推,按照左根右压倒栈里面了。一个一个再出栈。
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode node = root;
while(node != null || !stack.isEmpty()){
while(node != null){
stack.add(node);
node = node.left;
}
node = stack.pop();
list.add(node.val);
node = node.right;
}
return list;
}
}
144.二叉树的前序遍历
和中序遍历类似,但是是根左右的顺序输出,所以在找最左的时候就应该都压进栈,这样保证根最先被压进来。
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
while(!stack.isEmpty() || root != null){
while(root != null){
stack.push(root);
list.add(root.val);
root = root.left;
}
root = stack.pop();
root = root.right;
}
return list;
}
}
145.二叉树的后序遍历
用迭代解决二叉树的后序遍历麻烦一定,因为是左右根的顺序输出,所以得判断这个有没有右,出栈了之后根节点的右访问没访问过的事情。添加到list中后将节点制空来让栈再推一个出来回跳查右。
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<Integer>();
TreeNode temp = new TreeNode();
Stack<TreeNode> stack = new Stack<>();
while(root!=null || !stack.isEmpty()){
while(root != null){
stack.push(root);
root = root.left;
}
root = stack.pop();
if(root.right == null || root.right == temp) {
temp = root;
ans.add(root.val);
root = null;
}else{
stack.push(root);
root = root.right;
}
}
return ans;
}
}