Easy to understand traversal approach Java


  • 0
    H
    class Solution {
        private TreeNode lcaNode = null;
        public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
            lcaNode = null;
            dfs(root, p, q);
            return lcaNode;
        }
        private boolean dfs(TreeNode root, TreeNode p, TreeNode q){
            if(root == null) return false;
            boolean left = dfs(root.left, p, q);
            boolean right = dfs(root.right, p, q);
            boolean rootFlag = (root==p || root==q);
            if(left&&right || left&&rootFlag || right&&rootFlag){
                lcaNode = root;
            }
            return left||right||rootFlag;
        } 
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.