![](https://img-blog.csdnimg.cn/direct/dc18a1ba1f6344c3a17ee6e93d87e1fc.png)
class Solution {
public void flatten(TreeNode root) {
Stack<TreeNode> st = new Stack<>();
if (root==null) return;
st.push(root);
TreeNode pre = null;
while(!st.isEmpty()){
TreeNode temp = st.pop();
if (pre!=null){
pre.right = temp;
pre.left = null;
}
if (temp.right!=null){
st.push(temp.right);
}
if (temp.left!=null) {
st.push(temp.left);
}
pre = temp;
}
}
}
class Solution {
TreeNode pre = null;
public void flatten(TreeNode root) {
if (root==null) return;
flatten(root.right);
flatten(root.left);
root.right = pre;
root.left = null;
pre = root;
}
}
![](https://img-blog.csdnimg.cn/direct/09237485ab944c509e44f5e6cb89c1fd.png)
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
return findNode(preorder,0,preorder.length,inorder,0,inorder.length);
}
public TreeNode findNode(int[] preorder, int prestart, int preend, int[] inorder, int instart, int inend){
if (prestart==preend) return null;
if (instart==inend) return null;
TreeNode root = new TreeNode(preorder[prestart]);
int inindex = 0; // 中序遍历的根节点
for (inindex=0;inindex<inend;inindex++){
if (inorder[inindex]==root.val){
break;
}
}
int leftlen = inindex - instart;
// 注意边界条件【先闭后开】
TreeNode left = findNode(preorder,prestart+1,prestart+1+leftlen,inorder,instart,inindex);
TreeNode right = findNode(preorder,prestart+1+leftlen,preend,inorder,inindex+1,inend);
root.left = left;
root.right = right;
return root;
}
}
![](https://img-blog.csdnimg.cn/direct/3ba63eb0ec32473a81ccffbbf39506a8.png)
class Solution {
public int pathSum(TreeNode root, long targetSum) {
if (root == null) {
return 0;
}
int ret = rootSum(root, targetSum);
ret += pathSum(root.left, targetSum);
ret += pathSum(root.right, targetSum);
return ret;
}
public int rootSum(TreeNode root, long targetSum) {
int ret = 0;
if (root == null) {
return 0;
}
int val = root.val;
if (val == targetSum) {
ret++;
}
ret += rootSum(root.left, targetSum - val);
ret += rootSum(root.right, targetSum - val);
return ret;
}
}
![](https://img-blog.csdnimg.cn/direct/82f04ce779d240989215985b33460b77.png)
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root==null || root==p || root==q) return root;
TreeNode left = lowestCommonAncestor(root.left,p,q);
TreeNode right = lowestCommonAncestor(root.right,p,q);
if (left==null && right!=null){
return right;
}else if (left!=null && right==null){
return left;
}else if (left==null && right==null){
// 说明左右子树都不包含p,q
return null;
}
return root;
}
}