513. 找树左下角的值
- 方法一:层序遍历(迭代法)
/**
class Solution {
public int findBottomLeftValue(TreeNode root) {
//本题使用迭代法(层序遍历)即可较为简单的得到答案
Queue<TreeNode> que = new LinkedList<>();
int res = 0 ;
//题目中保证了二叉树至少有一个节点
que.offer(root);
while(!que.isEmpty()){
int len = que.size();
for(int i= 0 ;i < len ; i++){
TreeNode temp = que.poll();
if(i == 0){
res = temp.val;
}
if(temp.left != null){
que.offer(temp.left);
}
if(temp.right != null){
que.offer(temp.right);
}
}
}
return res;
}
}
2. 方法二:递归法:
class Solution {
private int DEEP = -1;
private int value = 0 ;
//private int deep ;
public int findBottomLeftValue(TreeNode root) {
//使用递归法
value = root.val;
findleftvalue(root,0);
return value;
}
private void findleftvalue(TreeNode root, int deep){
if(root == null){
return ;
}
//终止条件
if(root.left == null && root.right == null){
if(deep > DEEP){
value = root.val;
DEEP = deep;
}
}
if(root.left != null){
findleftvalue(root.left, deep + 1);
}
if(root.right != null){
findleftvalue(root.right,deep + 1);
}
}
}
112. 路径总和
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
if (root == null) {
return false;
}
targetSum -= root.val;
// 叶子结点
if (root.left == null && root.right == null) {
return targetSum == 0;
}
if (root.left != null) {
boolean left = hasPathSum(root.left, targetSum);
if (left) { // 已经找到
return true;
}
}
if (root.right != null) {
boolean right = hasPathSum(root.right, targetSum);
if (right) { // 已经找到
return true;
}
}
return false;
}
}
106. 从中序与后序遍历序列构造二叉树
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
return create(inorder,0,inorder.size()-1,postorder,0,postorder.size()-1);
}
TreeNode* create(vector<int>& inorder,int instart,int inend, vector<int>& postorder,int poststart, int postend){
if(instart>inend){
return nullptr;
}
//首先找到再中序遍历中的根节点的序号
int rootval = postorder[postend];
int index = 0;
for( int i = instart ;i <= inend ; i++){
if(rootval==inorder[i]){
index = i;
break;
}
}
//现在得到了中序遍历中的根节点和序号
int leftsize = index - instart ;
TreeNode* root = new TreeNode(rootval);
root->left = create(inorder,instart,index-1,postorder,poststart,poststart+leftsize-1);
root->right = create(inorder,index+1,inend,postorder,poststart+leftsize,postend-1);
return root;
}
};