根节点路径问题

方法一:bottom-up

Node *LCA(Node *root, Node *p, Node *q) {
  if (!root) return NULL;
  if (root == p || root == q) return root;
  Node *left = LCA(root->left, p, q);
  Node *right = LCA(root->right, p, q);
  if (left && right) return root;  // if p and q are on both sides
  return left ? left :right ;  // either one of p,q is on one side OR p,q is not in L&R subtrees
}

方法二:

TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
     if(root==NULL||p==NULL||q==NULL)  return NULL;

     vector<TreeNode*>s1;
     vector<TreeNode*>s2;
     bool left=findpath(root,p,s1);
     bool right=findpath(root,q,s2);
     int i;
     if(left&&right){
        for( i=0;i<s1.size()&&i<s2.size();i++){
            if(s1[i]!=s2[i])  break;
        }
        return s1[i-1];

    }
    else return NULL;

    }
    bool  findpath(TreeNode*root,TreeNode*p,vector<TreeNode*>&s1){
        TreeNode*cur=root;
        TreeNode*prev=NULL;
        while(cur!=NULL||!s1.empty()){
            while(cur!=NULL){
                s1.push_back(cur);
                cur=cur->left;

            }
            cur=s1.back();
            if(cur->right==NULL||cur->right==prev){
                if(cur==p){

                    return true;
                }
                prev=cur;
                cur=NULL;
                s1.pop_back();
            }
            else
                cur=cur->right;
        }
        return false;
    }

方法三:

TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {

    if(root==NULL||p==NULL||q==NULL)  return NULL;

    vector<TreeNode*>s1;
    vector<TreeNode*>s2;
    bool left=findpath(root,p,s1);
    bool right=findpath(root,q,s2);
    int i;
    if(left&&right){
        for( i=0;i<s1.size()&&i<s2.size();i++){
            if(s1[i]!=s2[i])  break;
        }
        return s1[i-1];

    }
    else return NULL;

}

       bool findpath(TreeNode*root,TreeNode*p,vector<TreeNode*>&s){
        if(root==NULL)  return false;
        s.push_back(root);
        if(root==p) return true;
        bool left=findpath(root->left,p,s);
        bool right=findpath(root->right,p,s);
        if(left||right) return true;
        s.pop_back();
        return false;

    }
时间: 2024-10-26 15:53:02

根节点路径问题的相关文章

二叉树中所有的路径(从根节点到叶子结点)

1 import java.util.ArrayList; 2 3 /** 4 * 寻找最短的二叉搜索的路径,从根节点到叶子结点 5 * 6 * @author jinfeng 7 * 8 */ 9 public class FindShortestBTPath { 10 11 // 用来记录所有的路径 12 private ArrayList<ArrayList<Integer>> allPaths = new ArrayList<ArrayList<Integer&

设计一个算法,输出从每个叶子节点到根节点的逆路径

下面使用三种遍历方法输出逆路径,假设二叉树采用二叉链存储结构存储. 方法1:采用基于层次遍历的方法,设计的队列为非环形顺序队列,将所有已扫描的节点指针进队,并在队列中保存双亲节点的位置.当找到一个叶子节点时,在队列中通过双亲节点的位置输出该叶子节点到根节点的逆路径.对应的算法如下: void AllPath(BTNode * b) { struct snode { BTNode *node; //存放当前节点指针 int parent; //存放双亲节点在队列中的位置 } Qu[MaxSize]

LeetCode:Path Sum - 树的根节点到叶节点的数字之和

1.题目名称 Path Sum(树的根节点到叶节点的数字之和) 2.题目地址 https://leetcode.com/problems/path-sum/ 3.题目内容 英文:Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. 中文:给定一颗二叉树,如

Dragon Balls HDU杭电3635 【并查集,递归的方法找根节点】

Problem Description Five hundred years later, the number of dragon balls will increase unexpectedly, so it's too difficult for Monkey King(WuKong) to gather all of the dragon balls together. His country has N cities and there are exactly N dragon bal

(hdu step 5.1.5)Dragon Balls(求并查集的根节点、节点数和个结点的移动次数)

题目: Dragon Balls Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 562 Accepted Submission(s): 239   Problem Description Five hundred years later, the number of dragon balls will increase unexpected

The Suspects(并查集维护根节点信息)

The Suspects Time Limit: 1000MS   Memory Limit: 20000K Total Submissions: 37090   Accepted: 17980 Description Severe acute respiratory syndrome (SARS), an atypical pneumonia of unknown aetiology, was recognized as a global threat in mid-March 2003. T

ORACLE 树形遍历查询根节点、父节点、子节点

1.准备演示数据 创建表结构: -- Create table createtable Z_ORG(  cid         NUMBER,  cname       VARCHAR2(32),  parent_id   NUMBER,  create_time DATE,  org_level   NUMBER) tablespace POWERDESK pctfree10 initrans1 maxtrans255; -- Add comments to the table comment

ztree树 叶子节点路径的集合

1.Question Description: ztree树各个节点都带有路径,如“/根节点”,"/根节点/一级节点",“根节点/一级节点/二级节点‘; 现在想获取所选的最末级节点数据集合. 2.Solution: $("#btn_saveAssetInfo").click(function(){ var treeObj = $.fn.zTree.getZTreeObj("toggle"); var nodes = treeObj.getChec

【JSTREE】 jstree-初始化时默认选中根节点

var contacttree = $('#contact-org').jstree({ "core" : { "animation" : false, "multiple" : false, "check_callback" : true, "themes" : { "icons" : true, "dots" : false }, "data"