leetcode 513 左下角的节点值
public static int findBottomLeftValue(TreeNode root){
int res =0;
Deque<TreeNode> que = new LinkedList();
if(root==null) return res;
que.offer(root);
res = root.val;
while(!que.isEmpty()){
int len = que.size();
for(int i=0;i<len;i++){
TreeNode tmp = que.poll();
if(i==0 ) {
res = tmp.val;// 就比层序遍历多了这里一点点,每层我都保留一下最左
}
if(tmp.left!=null) que.offer(tmp.left);
if(tmp.right!=null) que.offer(tmp.right);
}
}
return res;
}
leetcode 112 路径总和
public static boolean hasPathSum(TreeNode root,int targetSum){
boolean res = false;
if(root==null) return false;
if(root.left==null &&root.right==null && 0==targetSum-root.val) return true;
boolean left=false;
if(root.left!=null){
left = hasPathSum(root.left,targetSum-root.val);
}
boolean right = false;
if(root.right!=null){
right = hasPathSum(root.right,targetSum-root.val);
}
return left||right;
}
leetcode 106 中序和后序数组确定唯一二叉树
思路是递归
我的代码还有优化空间...
public static TreeNode buildTree(int[] inOrder,int[] postOrder){
TreeNode root=null;
if(inOrder.length==1 && postOrder.length==1 && inOrder[0]==postOrder[0])
return new TreeNode(inOrder[0]);
// if(inOrder.length!=postOrder.length) return null;
int i=0;
int val = postOrder[postOrder.length-1];
for(i=0;i<inOrder.length;i++){
if(inOrder[i]==val) {
root = new TreeNode(val);
break;
}
}
root.left = buildTreeSub(inOrder, 0, 0 + i - 1, postOrder, 0, 0 + i - 1);
root.right = buildTreeSub(inOrder, 0 + i + 1, inOrder.length-1, postOrder, 0 + i, postOrder.length-1 - 1);
return root;
}
private static TreeNode buildTreeSub(int[] inOrder, int startIn, int endIn, int[] postOrder, int startPost, int endPost) {
//TreeNode root = new TreeNode(postOrder[endPost]);
if(startIn>endIn || startPost>endPost) return null;
if(startIn==endIn && startPost==endPost)
return new TreeNode(inOrder[startIn]);
int i=0;
int val = postOrder[endPost];
TreeNode root=null;
for(i=0;i<inOrder.length;i++){
if(inOrder[i]==val) {
root = new TreeNode(val);
break;
}
}
int leftLen = i-startIn;
int rightLen = endIn-i;
if(root!=null) {
root.left = buildTreeSub(inOrder, startIn, i - 1, postOrder, startPost, startPost + leftLen-1);
root.right = buildTreeSub(inOrder, + i + 1, endIn, postOrder, endPost-rightLen, endPost - 1);
}
return root;
}