leetcode 236 (DFS in a tree)

 Thoughts on leetcode 236

Traverse the tree in a depth first manner. The moment you encounter either of the nodes p or q, return some boolean flag. The flag helps to determine if we found the required nodes in any of the paths. The least common ancestor would then be the node for which both the subtree recursions return a True flag. It can also be the node which itself is one of p or q and for which one of the subtree recursions returns a True flag. (the reason why we create the variable 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) {
        found(root, p, q);
        return ans;
    }
    public boolean found(TreeNode root, TreeNode p, TreeNode q){
        if(root == null){
            return false;
        }
        //check if the current node is the target node
        int cur = (root == p || root == q) ? 1 : 0;
        //check if the left and right branches
        int left = found(root.left, p, q) ? 1 : 0;
        int right = found(root.right, p, q) ? 1 : 0;
        if(cur + left + right == 2){
            ans = root;
        }
        return (cur + left + right) == 1;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值