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;
    }
}

上一篇:leetcode 236. 二叉树的最近公共祖先


下一篇:GitHub上的“金矿”(236个Python开源项目,涵盖了15个领域)