leetcode 129, 236 (dfs in a tree)
作者:互联网
Solution for leetcode 129
https://leetcode.com/problems/sum-root-to-leaf-numbers/
class Solution {
public int sumNumbers(TreeNode root) {
return dfs(root, 0);
}
public int dfs(TreeNode node, int num){
if(node == null){
return 0;
}
int cur = num * 10 + node.val;
if(node.left == null && node.right == null){
return cur;
}
return dfs(node.left, cur) + dfs(node.right, cur);
}
}
Solution for leetcode 236
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/
class Solution {
TreeNode ans = null;
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
dfs(root, p, q);
return ans;
}
public boolean dfs(TreeNode root, TreeNode p, TreeNode q){
if(root == null){
return false;
}
//在当前节点
boolean inCurrentNode = root.val == p.val || root.val == q.val;
//在左节点
boolean inLeft = dfs(root.left,p,q);
//在右节点
boolean inRight = dfs(root.right,p,q);
if((inLeft && inRight) || (inCurrentNode && (inLeft || inRight))){
ans = root;
}
return inLeft || inRight || inCurrentNode;
}
}
标签:node,TreeNode,tree,dfs,return,129,236,null,root 来源: https://blog.csdn.net/weixin_41917137/article/details/118876466