zoukankan      html  css  js  c++  java
  • leetcode@ [236] Lowest Common Ancestor of a Binary Tree(Tree)

    https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/

    Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

    According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”

    For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        void findPath(TreeNode* root, vector<TreeNode* >& load, vector<TreeNode* >& path, TreeNode* p) {
            if(root == NULL) return;
            if(root == p) {
                path = load;
                return;
            }
            
            load.push_back(root->left);
            findPath(root->left, load, path, p);
            load.pop_back();
            
            load.push_back(root->right);
            findPath(root->right, load, path, p);
            load.pop_back();
        }
        void reverse_vector(vector<TreeNode* > v) {
            vector<TreeNode* > res; res.clear();
            
            for(int i=v.size()-1;i>=0;--i) res.push_back(v[i]);
            v = res;
        }
        TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
            if(p == q) return p;
            
            vector<TreeNode* > load1, load2, path1, path2;
            
            TreeNode *r = root;
            load1.push_back(r);
            load2.push_back(r);
            
            findPath(r, load1, path1, p);
            findPath(r, load2, path2, q);
            
            reverse_vector(path1); 
            reverse_vector(path2); 
            
            int i = 0, j = 0, m = path1.size(), n = path2.size(), resi;
            cout << m << n << endl;
            while(i < m && j < n && path1[i] == path2[j]) {
                resi = i; ++i; ++j;
            }
            
            return path1[resi];
        }
    };
    leetcode: 236
  • 相关阅读:
    DOM操作 append prependTo after before
    Vue(2)- v-model、局部组件和全局组件、父子组件传值、平行组件传值
    Vue(1)- es6的语法、vue的基本语法、vue应用示例,vue基础语法(转)
    Linux环境下虚拟环境virtualenv安装和使用(转)
    REST、DRF(View源码解读、APIView源码解读)
    超哥的 LINUX 入门大纲
    redis入门
    CRM总结
    如何搭建一个vue项目(完整步骤)
    DRF 视图
  • 原文地址:https://www.cnblogs.com/fu11211129/p/5096600.html
Copyright © 2011-2022 走看看